问题描述
有没有办法告诉 gcc 抛出 SIGFPE 或类似的东西来响应在运行时导致 NaN
或 (-)inf
的计算,就像它会被零除吗?
Is there a way to tell gcc to throw a SIGFPE or something similar in response to a calculation that results in NaN
or (-)inf
at runtime, like it would for a divide-by-zero?
我尝试了 -fsignaling-nans
标志,但似乎没有帮助.
I've tried the -fsignaling-nans
flag, which doesn't seem to help.
推荐答案
几乎任何从非 NaN 输入产生 NaN 的浮点运算或数学库函数也应该发出无效运算"浮点异常的信号;同样,从有限输入产生无穷大的计算通常会发出被零除"或溢出"浮点异常的信号.因此,您需要某种方式将这些异常转换为 SIGFPE.
Almost any floating-point operation or math library function that produces a NaN from non-NaN inputs should also signal the 'invalid operation' floating-point exception; similarly, a calculation that produces an infinity from finite inputs will typically signal either the 'divide-by-zero' or 'overflow' floating-point exception. So you want some way of turning these exceptions into a SIGFPE.
我怀疑答案将高度依赖于系统,因为浮点陷阱和标志的控制可能由平台 C 库而不是 gcc 本身提供.但这是一个适用于我的例子,在 Linux 上.它使用 fenv.h
中的 feenableexcept
函数._GNU_SOURCE
定义是声明此函数所必需的.
I suspect the answer will be highly system-dependent, since control of floating-point traps and flags is likely to be supplied by the platform C library rather than by gcc itself. But here's an example that works for me, on Linux. It uses the feenableexcept
function from fenv.h
. The _GNU_SOURCE
define is necessary for this function to be declared.
#define _GNU_SOURCE
#include <fenv.h>
int main(void) {
double x, y, z;
feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
x = 1e300;
y = 1e300;
z = x * y; /* should cause an FPE */
return 0;
}
警告:我认为在某些设置下,异常可能直到 next 浮点操作之后才真正生成(理论上)应该导致它,所以你有时需要无操作浮点运算(例如乘以 1.0)来触发异常.
A caveat: I think it's possible with some setups that the exception isn't actually generated until the next floating-point operation after the one that (in theory) should have caused it, so you sometimes need a no-op floating-point operation (e.g. multiplying by 1.0) to trigger the exception.
这篇关于我可以让 gcc 在运行时告诉我计算结果是 NaN 还是 inf 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!