今天碰到一个奇怪的报错:No previous prototype for function 'MyAdd'
下面贴下源码:
main.m文件中
int MyAdd()
{
return 0;
}
int main (int argc,constchar * argv[])
{//这里省略不重要的代码
return 0;
}
编译的时候报了上面的错误。查了下,说是要再头文件中做下声明,于是又再头文件中声明了下,再次编译,还是报错。再次查了下,又发现有人说在函数前面加上static就可以解决了,果然,加了后确实解决了。问题是解决了,但是为什么会这样?在c语言中,这样的用法是很正常的,但是在objective c中就不行了。仔细查了资料发现了问题的所在。
这里有2个问题:
1,MyAdd()函数是没有参数的,这里需要明确的表示出来,也就是需要加上void,这里是需要声明的
2,static能够解决,表明这是一个在本文件中使用的函数,也是可以不用声明的
具体为什么能够会这样,还是有点模糊,下次再查下资料。
纪录下
刚刚再次查了下,发现下面的答案:
This means that GCC found a global function definition without seeing a prototype for the function. If a function is used in more than one file, there should be a prototype for it in a header file somewhere. This keeps functions and their uses from getting out of sync
If the function is only used in this file, make it static to guarantee that it'll never be used outside this file and document that it's a local function
大意就是说gcc如果认为他是全局的函数,就必须要再.h中声明,否则就只能在本文件中使用,也就需要加上static。
这下该满足了吧