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

时间:2019-01-08 17:38:00

标签: fortran gfortran

以下简单代码:

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.

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

(实际上是在调试一个更大的代码,我需要陷阱才能在代码的其他地方找到问题。但是我需要克服这个琐碎的输入语句,在那里它们以某种方式使我绊倒)

1 个答案:

答案 0 :(得分:2)

如果您确实想在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