Gfortran: Treat pure functions as normal functions

2019-02-21 23:35发布

问题:

I need to debug some pure functions in a fortran Program compiled with gfortran. Is there any way to ignore the pure statements so I can use write, print, etc. in these pure functions without great effort? Unfortunately it is not easly possible to just remove the pure statement.

回答1:

You can use a macro and use the -cpp flag.

#define pure 

pure subroutine s
 print *,"hello"
end


回答2:

I usually use the pre-processor for this task:

#ifdef DEBUG
subroutine test(...)
#else
pure subroutine(...)
#endif
  ! ...
#ifdef DEBUG
  write(*,*) 'Debug output'
#endif
  ! ...
end subroutine

Then you can compile your code with gfortran -DDEBUG for verbose output. (In fact I personally do not set this flag globally, but via #define DEBUG at the beginning of the file I want debug).

I also have a MACRO defined to ease the use of debugging write statements:

#ifdef DEBUG
#define dwrite write
#else
#define dwrite ! write
#endif

With this, the code above reduces to:

#ifdef DEBUG
subroutine test(...)
#else
pure subroutine(...)
#endif
  ! ...
  dwrite (*,*) 'Debug output'
  ! ...
end subroutine

You can enable the pre-processor with -cpp for gfortran, and -fpp for ifort. Of course, when using .F90 or .F, the pre-processor is enabled by default.