Fortran: Is there a way to conditionally use modules?
Asked Answered
V

2

6

Assume I have two Fortran modules called modA and modB. Is there a way to use one or the other in a program based on a conditional statement? Does this require some type of preprocessing? For example, I want to be able to do something like the following code:

if (condition)
    use modA
else
    use modB
end

I am using the GNU Fortran compiler.

Vasileior answered 13/5, 2016 at 21:19 Comment(0)
D
7

Yes, you must do some kind of preprocessing. The most common is the C preprocessor included in GNU Fortran.

#if (condition)
    use modA
#else
    use modB
#endif

The preprocessor does not understand your Fortran code, it is only a text for it. It has it's own set of directives and it's own set of variables. Only the preprocessor variables can be used in the condition, not your Fortran variables.

Another common directive is #ifdef which is a variant of #if defined. See the manual for more https://gcc.gnu.org/onlinedocs/cpp/Traditional-Mode.html (gfortran runs the preprocessor in the traditional mode).

To enable the preprocessor use the -cpp flag or in Unix you can use capital F in the file suffix.

Dignitary answered 13/5, 2016 at 21:33 Comment(0)
K
0

You could consider using both modules and add the logic elsewhere provided that you can solve the problem in pure Fortran without preprocessing.

However, if you are addressing a portability issue preprocessing might might be your best shot. For example, if you want to be able to compile a code that uses GNU extensions with both the GNU Fortran Compiler and the the Intel Fortran Compiler you would use a preprocessing directive such as this one to address that:

#if defined(__INTEL_COMPILER)
  use :: ifport
#endif

The Intel Fortran Portability module is used only when the __INTEL_COMPILER macro is defined and that happens when you are compiling the source with the Intel Fortran Compiler.

I am sharing a link to one of my GitHub repositories where I use preprocessing for anyone interested in looking at more examples.

Kutchins answered 9/11, 2023 at 16:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.