C 中的隐式函数声明 [英] Implicit function declarations in C

查看:40
本文介绍了C 中的隐式函数声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

术语函数的隐式声明"是什么意思?在不包含适当头文件的情况下调用标准库函数会产生警告,如以下情况:

What is meant by the term "implicit declaration of a function"? A call to a standard library function without including the appropriate header file produces a warning as in the case of:

int main(){
  printf("How is this not an error?");
  return 0;
}

不应该使用函数而不声明它是错误的吗?请详细说明.我搜索了这个网站,发现了类似的问题,但找不到明确的答案.大多数答案都提到了包含头文件以消除警告的内容,但我想知道这不是错误.

Shouldn't using a function without declaring it be an error? Please explain in detail. I searched this site and found similar questions, but could not find a definitive answer. Most answers said something about including the header file to get rid of the warning, but I want to know how this is not an error.

推荐答案

应该被认为是一个错误.但是 C 是一种古老的语言,所以它只是一个警告.
使用 -Werror (gcc) 编译修复了这个问题.

It should be considered an error. But C is an ancient language, so it's only a warning.
Compiling with -Werror (gcc) fixes this problem.

当 C 没有找到声明时,它会假定这个隐式声明:int f();,这意味着该函数可以接收你给它的任何东西,并返回一个整数.如果这恰好足够接近(在 printf 的情况下,它是),那么事情就可以工作了.在某些情况下(例如函数实际上返回一个指针,并且指针大于整数),可能会造成真正的麻烦.

When C doesn't find a declaration, it assumes this implicit declaration: int f();, which means the function can receive whatever you give it, and returns an integer. If this happens to be close enough (and in case of printf, it is), then things can work. In some cases (e.g. the function actually returns a pointer, and pointers are larger than ints), it may cause real trouble.

请注意,这已在较新的 C 标准(C99、C11)中修复.在这些标准中,这是一个错误.但是,gcc 默认不实现这些标准,所以你仍然会收到警告.

Note that this was fixed in newer C standards (C99, C11). In these standards, this is an error. However, gcc doesn't implement these standards by default, so you still get the warning.

这篇关于C 中的隐式函数声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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