[英]When using fabs, fmin, fmax in a C program, why doesn't the compiler/linker report an error if math.h is not included?
When compiling a C program in Visual Studio 2013 the following may produce different results:在 Visual Studio 2013 中编译 C 程序时,以下结果可能会产生不同的结果:
#include <math.h>
void bar(void) {
double f = fabs(-1.0);
/* f is 1.0 */
}
and和
void foo(void) {
double f = fabs(-1.0);
/* f is 0 */
}
and the same snippet without including math.h .和不包括 math.h的相同片段。 When omitting the include, the compiler does not report an error and assumes
fabs
has the following signature int fabs()
.省略包含时,编译器不会报告错误并假定
fabs
具有以下签名int fabs()
。
Is there anyway to force the compiler to report this as an error or even a warning?有没有强制编译器将此报告为错误甚至警告?
In older C standards if a function is used before it's declared then it's assumed to receive an unknown number of arguments (under default promotion like in variadic functions such as printf
) and return int
.在较旧的 C 标准中,如果函数在声明之前使用,则假定它接收未知数量的参数(在默认提升下,如
printf
等可变参数函数)并返回int
。 The compiler will expect the symbol to be fixed later during linking stage so no errors should be reported编译器希望在链接阶段稍后修复符号,因此不应报告错误
So without including math.h
the compiler doesn't know the prototype of fabs
and will assume that it accepts any kinds of parameters and returns int
.因此,如果不包含
math.h
,编译器不知道fabs
的原型,并且会假设它接受任何类型的参数并返回int
。 Then when linking the linker really found a symbol with the expected name and resolves to that function, but due to the mismatch in the function signature the behavior is undefined .然后当链接器真正找到一个具有预期名称的符号并解析为该函数时,但由于函数签名中的不匹配,行为是 undefined 。 Turn on all warnings and you'll see something about implicit return type
打开所有警告,你会看到一些关于隐式返回类型的信息
In VS2013 I got the below warning even without increasing the warning level在 VS2013 中,即使没有增加警告级别,我也收到以下警告
Warning 1 warning C4013: 'fabs' undefined; assuming extern returning int
For more information read欲了解更多信息,请阅读
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.