2

I know how to use IF and ENDIF in Fortran, but in many codes I have from others, there is a # sign before the IF, what does that mean?

!USES:
#if ( defined X )
     use Y
#endif
Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68
newbie
  • 757
  • 1
  • 9
  • 19
  • In addition to the points in the answers, it could be useful to note: relating to preprocessing their placement/use is not subject to the rules of the `if` construct/statement of Fortran. Which is why you can have a `use` statement done conditionally this way. – francescalus Sep 16 '16 at 16:55
  • Depending on the Fortran compiler, cpp-like preprocessing is invoked by a command line option -fpp or -cpp or by capitalization of file name suffix .F90 or .F or by a GUI project setting. Without that, the # directives will be flagged as errors. – tim18 Sep 17 '16 at 11:28

2 Answers2

6

These are pre-compiler macros, and not Fortran statements. They do the same as regular if statements, only at compile time and with a slightly different syntax.

Note that pre-processor directives are not part of any Fortran Standard, and that they are not supported by every compiler. Generally, they are identical to C pre-processor directives, but not always.

Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68
4

#ifdef and #endif are preprocessor directives.

suppose you had a file:

! test.F:
     program A
     x=1
#ifdef NEW
     x=0
#endif
     write(*,*) x
     end

if you compile it using a preprocessor:

    ifort -DNEW test.F -o a.out

you should get x =0

otherwise if you compile without -DNEW like

    ifort test.F -o a.out

in that case you get x=1. The code inside the ifdef is not compiled. Here are compile time options for gfortran.. A useful situation for example is this question.

Community
  • 1
  • 1
wander95
  • 1,298
  • 1
  • 15
  • 22