What are the implications of having an “implicit declaration of function” warning in C?

喜夏-厌秋 提交于 2021-02-19 03:49:50

问题


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 of function 'funcA'

$ gcc -Wall -Wextra file1.o file2.o -o test.exe
$ ./test.exe
hello world

回答1:


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.



来源:https://stackoverflow.com/questions/2688333/what-are-the-implications-of-having-an-implicit-declaration-of-function-warnin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!