What are the implications of having an "implicit declaration of function" warning in C?
As the question states, what exactly are the implications of having the 'implicit declaration of function' warning? We just cranked up the warning flags on gcc and found quite a few instances of these warnings and I'm curious what type of problems this may have caused prior to fixing them?
Also, why is this a warning and not an error. How is gcc even able to successfully link this executable? As you can see in the example below, the executable functions as expected.
Take the following two files for example:
file1.c
#include <stdio.h>
int main(void)
{
funcA();
return 0;
}
file2.c
#include <stdio.h>
void funcA(void)
{
puts("hello world");
}
Compile & Output
$ gcc -Wall -Wextra -c file1.c file2.c
file1.c: In function 'main':
file1.c:3: warning: implicit declaration o开发者_如何学JAVAf function 'funcA'
$ gcc -Wall -Wextra file1.o file2.o -o test.exe
$ ./test.exe
hello world
If the function has a definition that matches the implicit declaration (ie. it returns int
and has a fixed number of arguments, and does not have a prototype), and you always call it with the correct number and types of arguments, then there are no negative implications (other than bad, obsolete style).
ie, in your code above, it is as if the function was declared as:
int funcA();
Since this doesn't match the function definition, the call to funcA()
from file1.c
invokes undefined behaviour, which means that it can crash. On your architecture, with your current compiler, it obviously doesn't - but architectures and compilers change.
GCC is able to link it because the symbol representing the function entry point doesn't change when the function type changes (again... on your current architecture, with your current compiler - although this is quite common).
Properly declaring your functions is a good thing - if for no other reason than that it allows you to give your function a prototype, which means that the compiler must diagnose it if you are calling it with the wrong number or types of arguments.
It has the same behaviour as using a non-prototype function declaration at block scope with an int
return type, because the return type can't be specified it defaults to int
, like all declarations in C that do not specify a type, everything is an int
.
The reason that functions can be implicitly declared is because they can only be defined at file scope, but it is unclear whether an undefined variable is block scope or file scope, therefore it is disallowed as opposed to selecting one and providing an implicit tentative definition at file or block scope. Indeed, the actual implict declaration is a block scope one, so you'll get a warning for the first reference to the function in each function it is referenced in.
精彩评论