非常简单的 Fortran 代码在使用 gfortran + fpe 陷阱标志编译时会产生错误

Very simple Fortran code produces error when compiled with gfortran + fpe trap flags

下面简单的代码:

program small_test
double precision :: a, b, c, d 
open(5,file='infile.dat',status='old')
READ (5,*) a, b, c, d
print *, a, b, c, d
end program

当我用 gfortran 编译时工作正常,没有陷阱标志:

$> gfortran  small_test.f90

输入数据为

0.087266463 0.087266463   3. 100.

输出为

   8.7266463000000002E-002   8.7266463000000002E-002   3.0000000000000000        100.00000000000000

符合预期。

但是当我编译时捕获浮点错误,

gfortran -ffpe-trap=invalid,zero,overflow,underflow,precision,denormal -fdump-core small_test.f90

代码因错误而失败

Program received signal SIGFPE: Floating-point exception - erroneous arithmetic operation.

这么简单的代码怎么可能会产生错误?

(真正发生的事情是我正在调试一个更大的代码,我需要陷阱来找到代码中其他地方的一些问题。但我需要通过这个微不足道的输入语句,他们在那里绊倒了我以某种方式上升。)

如果您真的认为要在 ieee_inexact 上启用浮点陷阱,那么您可能应该使用 Fortran 语言提供的工具来控制异常,而不是编译器选项。尝试

program small_test
   use ieee_arithmetic
   implicit none
   double precision :: a, b, c, d
   logical flag
   open(5,file='infile.dat',status='old')
   if (ieee_support_flag(ieee_inexact)) then
      call ieee_get_halting_mode(ieee_inexact, flag)
      call ieee_set_halting_mode(ieee_inexact, .false.)
   end if
   read (5,*) a, b, c, d
   print *, a, b, c, d
   if (ieee_support_flag(ieee_inexact)) then
      call ieee_set_halting_mode(ieee_inexact, flag)
   end if
end program