可我做的gcc告诉我,当计算结果NaN或INF在运行时? [英] Can I make gcc tell me when a calculation results in NaN or inf at runtime?

查看:180
本文介绍了可我做的gcc告诉我,当计算结果NaN或INF在运行时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法告诉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-NaN的标志,它似乎并没有帮助。

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;
}

一个警告:我认为这是可能的,这个例外是不实际直到的下次的浮点的(理论上)应该已经导致它一前一后的操作,让你产生了一些设置有时需要一个无操作浮点运算(例如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在运行时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆