6

I want to know if it is possible to select different parts of my Fortran 95 routine to compile.

For example, if I pass certain flag to gfortran, then the compiler chooses which section to use for a certain function. I know I can do it using if inside the routine, but the drawback is that I don't want the program to run the if all the time due to speed concerns. I suppose solution should be similar to this one

I am working specifically with a program that calculates energies in a many-body system (say, a million). Then I don't want to put an if each time that I need to use a different energy definition at compilation time.

I hope this is possible and that my question is clear.

Community
  • 1
  • 1
Nando
  • 170
  • 3
  • 9

1 Answers1

3

You can use the C like preprocessor. The -cpp command line option to your command line. That option is not turned on by default (As per Vladimir F comment below), although it looks like using the .F90 filename extension (i.e. capital F, instead of .f90) will do the trick without the -cpp option.

Details about the option:

https://gcc.gnu.org/onlinedocs/gfortran/Preprocessing-Options.html

Then you can do the same as you pointed out, so the:

#ifdef <some-var>
  code when <some-var> is true
#elif defined(<other-var>)
  code when <other-var> is true
#endif

As required.

There are more examples on this page with actual code.

Also, like with C/C++, you can define macros on your command line with the-D option:

gfortran -DCASE1=3 ...

This will define CASE1 with the value 3. If you do not specify the value, then 1 is automatically assigned to the macro. This is documented on the same page.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
  • 1
    Using the cpp preprocessor worked perfect. I had not idea this existed. Thanks a lot, Alexis! – Nando Jan 19 '17 at 00:52
  • 1
    I think `#elsif` is a typo. it should be `#elif` instead. – s.ouchene Aug 03 '21 at 16:26
  • The extension should be written with capital letters (i.e .F90 and not .f90). That’s the way most compilers automatically know that they should preprocess the code (quoted from the second link in your post). – s.ouchene Aug 03 '21 at 16:31
  • I applied both comments to my answer. Good catch for the `#elsif`. Also, you need the `defined()` to be equivalent to the `#ifdef`. – Alexis Wilke Aug 03 '21 at 18:07