Search code examples
modulefortranconditional-statementsgfortran

Fortran: Is there a way to conditionally use modules?


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.


Solution

  • 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.