我的编译器(GCC)给了我警告。
警告:函数的隐式声明
请帮助我理解为什么会出现这种情况。
你正在使用一个编译器还没有看到声明("prototype")的函数。
比如说。
int main()
{
fun(2, "21"); /* The compiler has not seen the declaration. */
return 0;
}
int fun(int x, char *p)
{
/* ... */
}
你需要在main之前声明你的函数,就像这样,直接或在头文件中声明。
int fun(int x, char *p);
正确的方法是在文件头中声明函数原型。
#ifndef MAIN_H
#define MAIN_H
int some_main(const char *name);
#endif
main.c
#include "main.h"
int main()
{
some_main("Hello, World\n");
}
int some_main(const char *name)
{
printf("%s", name);
}
有一个文件(main.c)的替代方案
static int some_main(const char *name);
int some_main(const char *name)
{
// do something
}
如果你定义了正确的头文件&;使用了非GlibC
库(如Musl C),gcc
也会在遇到malloc_trim
等GNU扩展时抛出错误:函数的隐式声明
。
解决方法是将扩展&包在头文件中。
#if defined (__GLIBC__)
malloc_trim(0);
#endif