C语言函数隐式声明——implicit declaration warning

implicit declaration of function——函数隐式声明警告

原因:
1、该函数未被声明,但却被调用了,此时gcc会报这样的警告信息。
2、(网友总结)该函数所在源文件没有被编译为.o二进制文件。

解决办法:
1、在调用之前先声明这个函数,一般使用extern关键字(该关键字非必需)
   声明函数可以不加extern,函数默认extern;声明变量必须要加extern。
2、将该函数声明在头文件中,然后在要调用的文件中包含该头文件
3、在c99、c11标准中,这被当做错误处理,而不是仅仅是警告。


根本原因:c语言中函数的隐式声明

在c语言中函数声明不是必须的,即使没有声明函数,gcc编译器也只是会提示警告。但是函数声明却是很有必要的。

那么函数声明到底有声明作用呢?

其实函数声明的作用是让编译器帮你检查函数调用时有没有错误。比如参数的数量是否正确,如果调用函数时候少传入一个参数,并且没有声明该函数,编译器无法知道你调用是否正确,只会提示一个警告。很多人会忽略警告,导致最后程序运行时出现异常。


为什么如果不声明函数,编译器发现不了错误?

编译器在编译过程中依次生成与源文件对应的可重定位目标文件(.o),每个源文件中调用的函数在链接前都是以符号的形式体现在.o文件中。在编译过程中不会去检查某个函数的形式,因为函数参数是通过寄存器和压栈来处理的,直接把函数翻译成符号,编译器是不知道关于函数参数的信息的,最后交给连接器把符号翻译成地址。所以链接的时候只要能找到对应得符号就不会报错。

从现代C语言的角度来说,任何标识符(除了goto的label以及main()的main)在使用之前都一定要声明,函数也是如此。
理论上这是必须的,但某些编译器为了迁就以前代码的一些写法放松了这个要求。所以还是应该写,尽管看起来貌似不是必须的。
--------------------- 


Implicit function declarations in C.
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. 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. 
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.

GCC只是默认还允许implicit function declaration功能而已,较新的C规范(C99、C11)是不允许不声明直接用的。

你可能感兴趣的:(C语言,implicit,declaration,gcc,warning,c语言,linux编译,隐式函数声明)