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
    use modB

I am using the GNU Fortran compiler.


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

    #if (condition)
        use modA
        use modB

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