为什么 LLVM 会抱怨缺少函数原型?
LLVM 2.1 有一个选项可以启用“缺少函数原型”的警告。启用后,警告将抱怨这样的文件:
double square( double d )
{
return d*d;
}
void main()
{
// ...
}
函数“square”将触发警告,因为它是在未声明(原型)的情况下定义的。您可以这样消除警告:
double square( double d );
double square( double d )
{
return d*d;
}
void main()
{
// ...
}
我用 C++ 编程已有二十年了,但从未见过这样的警告。这对我来说似乎没什么用。
默认情况下,此警告在 Xcode 4.1 中的新 Mac 控制台项目(至少)中启用。显然有人发现它足够有用,首先实现它,然后默认启用它。
为什么这是一个有用的警告?为什么 LLVM 有它作为一个选项?为什么 Xcode 上默认启用该选项?
LLVM 2.1 has an option that enables warnings for "missing function prototypes." When enabled, the warning will complain about a file like this:
double square( double d )
{
return d*d;
}
void main()
{
// ...
}
The function "square" will trigger a warning because it is defined without having been declared (prototyped). You can eliminate the warning thus:
double square( double d );
double square( double d )
{
return d*d;
}
void main()
{
// ...
}
I've programmed in C++ for twenty years and I've never seen a warning like this. It does not seem useful to me.
By default, this warning is enabled in new Mac console projects (at least) in Xcode 4.1. Evidently someone found it useful enough to first implement it and then enable it by default.
Why is this a useful warning? Why does LLVM have it as an option? Why is the option enabled by default on Xcode?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译器使用原型声明来匹配函数定义的类型。
如果您在头(接口)文件中编写原型并在源文件中编写实现,那么此警告(通过强制您有效地提供声明)将防止您在函数定义与函数定义不同的情况下犯错在声明中。
不过,如果没有这样的警告,您在链接时会收到错误。人们最终可能想知道实际问题是什么(链接错误的原因有很多)。
编译阶段的警告比链接错误更好地指示错误。
The compiler uses the prototype declaration to match types for the function definition.
If you are writing the prototype in a header(interface) file and the implementation in the source file then this warning (by forcing you to provide a declaration, effectively) would prevent you from making a typo error where function definition is different than the one in declaration.
Though, without such an warning, you would get the errors while linking. One might end up wondering what the actual problem is(n number of reasons for linking errors).
The warning during compilation stage is much better indication of error than a linking error.
如果可以确保每个函数在某个标头中可见或静态。
我遇到过两个文件链接在一起的情况,即使它们都没有使用相同的头文件。
举个例子:
如果没有标头,您可以有第二个文件:
如果您正在编写一个库,此警告可能会告诉您有人可能正在使用此函数,即使他们不应该这样做,因为此函数位于没有标题。它们应该被标记为静态。
If could be useful to make sure every function is either visible from some header, or static.
I had cases where two files were linked together, even though none of them used the same header file.
Take this example:
If there's no header, you can have a second file which does:
If you are writing a library, this warning could tell you that someone could be using this function even if they were not supposed to, since this function is in no header. They should have been marked as static.
“int test()”的原型应该是“int test(void)”就可以了。
Prototype of "int test()" should be "int test(void)" then it's OK.