简体   繁体   English

当在c中定义和声明的函数原型不同时,为什么没有警告?

[英]Why there is no warning when function prototype in definition and declaration are not the same in c?

I have three files, test.c , ah , ac . 我有三个文件, test.cahac test.c call a function declared in ah , and ac define the function. test.c调用在ah声明的函数,并用ac定义该函数。 But the funcion in ac are different from ah in the return value and the parameter. 但是ac中的函数在返回值和参数上与ah不同。 Either case, there is no warning from my gcc and there is some result. 无论哪种情况,我的gcc都不会发出警告,并且会产生一些结果。 Why? 为什么?

In my test.c 在我的test.c

#include "a.h"
#include <stdio.h>
int main(){
  int x = a();
  printf("%d\n", x);
}

In my ah 在我ah

int a();

In my ac 在我的ac

#include <stdio.h>

void a(int a)
{
    printf("%d\n", a);
}

in my terminal: 在我的终端中:

$ gcc -o test test.c a.c  // no warning
$ ./test
1
2

Without the ah being included in ac, the compiler doesn't know it's a problem. 如果没有ah包含在ac中,则编译器不知道这是一个问题。 So you won't get any compile issues at all. 因此,您根本不会遇到任何编译问题。 Each gets its own .o file and everyone is happy. 每个人都有自己的.o文件,每个人都很高兴。

The compiler expects a() to return an int so it has the machine code grab the result off the stack (or probably some register). 编译器期望a()返回一个int以便它使机器代码从堆栈(或可能的某个寄存器)中获取结果。

The compiler expects a() to have a parameter, so it has the machine code grab the parameter off the stack (again, probably a register). 编译器期望a()有一个参数,因此它使机器码将参数从堆栈中抢走(同样,可能是一个寄存器)。

Then the linker comes along and puts them all together. 然后链接器出现,并将它们放在一起。 It doesn't know that there's an issue, but it makes the call to a() work. 它不知道有问题,但是它使对a()的调用起作用。

So you get values that are left over on the register (or stack). 这样就得到了保留在寄存器(或堆栈)上的值。 And hopefully you're in a protected environment so that you're not getting some other user's information. 并希望您处于受保护的环境中,以免得到其他用户的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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