This is the mail archive of the
fortran@gcc.gnu.org
mailing list for the GNU Fortran project.
Best way to simulate C-assert using gfortran
- From: "Tilo Schwarz" <tilo at tilo-schwarz dot de>
- To: fortran at gcc dot gnu dot org
- Date: Sun, 03 Feb 2013 14:48:07 +0100
- Subject: Best way to simulate C-assert using gfortran
Hi,
I'm looking for a way to simulate C-assert using gfortran:
1. It should only generate code if NDEBUG is not defined (or some switch
is set/unset).
2. It should dump core (to inspect the problem in gdb), if the assertion
does not hold.
3. It should work in pure function too.
I did search google, but without real success.
Since pure functions can't call abort, I finally came up with generating a
floating point exception triggering the core dump (see below).
Now my questions are:
1. Is there a nicer way to get the same result, maybe using pure Fortran?
2. Is there maybe a trick which could be used specifically with gfortran
(maybe some gfortran/gcc intrinsic)?
Thanks!
Tilo
% cat prg_assert.f08
#ifdef NDEBUG
#define assert(expr)
#else
#define assert(expr) call assertion(expr)
#endif
program test
implicit none
real r(3), s(3)
s = [2.0, 1.0, 0.0]
r = f(s)
print *, r
contains
elemental real function f(x)
implicit none
real, intent(in) :: x
assert(x > 0)
f = x
end function f
pure subroutine assertion(cond)
implicit none
logical, intent(in) :: cond
real, volatile :: r
r = 1.0
if (.not. cond) r = r / 0.0
end subroutine assertion
end program test
% gfortran -ffpe-trap=zero -cpp -DNDEBUG prg_assert.f08; a.out
2.00000000 1.00000000 0.00000000
% gfortran -ffpe-trap=zero -cpp prg_assert.f08; a.out
Program received signal SIGFPE: Floating-point exception - erroneous
arithmetic operation.
Backtrace for this error:
#0 0xB7605503
#1 0xB7605BA0
#2 0xB76F23FF
#3 0x80486AD in assertion.1800 at prg_assert.f08:0
#4 0x80487C1 in f.1803 at prg_assert.f08:0
#5 0x80486F4 in MAIN__ at prg_assert.f08:0
Floating point exception (core dumped)