我希望我的代码在出现浮点错误时能够终止。在linux-gcc中,使用“feenableexcept()”函数可以完成此操作,但这在OSX上不可用。在OS X上使用gcc时,采用(Enabling floating point interrupts on Mac OS X Intel)中的方法可以正常工作,但是在使用clang时无法生效。
示例代码:
示例代码:
#include <stdio.h>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include <xmmintrin.h>
void handler(int sig) {
void *array[10];
size_t size;
size = backtrace(array, 10);
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(array, size, STDERR_FILENO);
exit(1);
}
int main(int argc, char **argv)
{
_MM_SET_EXCEPTION_MASK( ( _MM_EXCEPT_INVALID |
_MM_EXCEPT_DENORM |
_MM_EXCEPT_DIV_ZERO |
_MM_EXCEPT_OVERFLOW |
_MM_EXCEPT_UNDERFLOW |
_MM_EXCEPT_INEXACT ) );
signal(SIGSEGV, handler);
signal(SIGFPE, handler);
std::cout<<"Perform 1.0/0.0"<<std::endl;
double a = 1.0/0.0;
std::cout<<"1.0/0.0 didn't kill program, result is "<<a<<std::endl<<std::endl;
int* foo = (int*) - 1 ;// make a bad pointer
std::cout<<"Attempting to print a bad pointer"<<std::endl;
printf("%d\n", *foo);
std::cout<<"Bad pointer didn't kill program."<<std::ends;
}
使用gcc5进行编译,结果为:
Perform 1.0/0.0
Error: signal 8:
0 a.out 0x000000010f97cb7f _Z7handleri + 28
1 libsystem_platform.dylib 0x00007fff895c652a _sigtramp + 26
2 ??? 0x00007fff6eab6568 0x0 + 140735050114408
3 libdyld.dylib 0x00007fff936a15ad start + 1
很好。非常有效。然而,当使用clang编译(Apple LLVM版本7.3.0(clang-703.0.29)),结果是这样的:
Perform 1.0/0.0
1.0/0.0 didn't kill program, result is inf
Attempting to print a bad pointer
Error: signal 11:
0 a.out 0x000000010d501d1f _Z7handleri + 31
1 libsystem_platform.dylib 0x00007fff895c652a _sigtramp + 26
2 ??? 0x00007fff62b7e568 0x0 + 140734849607016
3 libdyld.dylib 0x00007fff936a15ad start + 1
效果不太好。没有触发FPE,代码仅继续运行。我已经查找了一些资料,但无法找到如何让clang触发FPE的方法。有人有相关经验吗?谢谢!