You can use the C preprocessor (CPP) in all major Fortran compilers. Usually there is a flag for invoking it (-cpp
in gfortran) or it is invoked automatically if the file suffix contains capital F (.F90
, .F
). The preprocessor allows more powerful inclusion of sources with the usage of macros.
module imod
use data_type, only: ivalue
#define T type(ivalue)
#include "template.f90"
#undef T
end module imod
module intmod
#define T integer
#include "template.f90"
#undef T
end module intmod
and template.f90
contains
subroutine printme(a)
implicit none
T :: a
print *,a
end subroutine printme
This is not strict f90 / f95, but it uses a preprocessor, included in the compilers, which produces another (strict f95) source file and it automatically compiles it instead of the original source that contains the macros.
The compilation is then straightforward
gfortran -cpp main.f90
--Edit--
For non-believers, if you want to see some real code using this, check https://github.com/LadaF/fortran-list (disclaimer: my own code). You can use the parametric linked list there as:
list of len(20) character strings:
module str_list
#define TYPEPARAM character(20)
#include "list-inc-def.f90"
contains
#include "list-inc-proc.f90"
#undef TYPEPARAM
end module
list of integers
module int_list
#define TYPEPARAM integer
#include "list-inc-def.f90"
contains
#include "list-inc-proc.f90"
#undef TYPEPARAM
end module
list of some derived type
module new_type_list
use, new_type_module, only: new_type
#define TYPEPARAM type(newtype)
#include "list-inc-def.f90"
contains
#include "list-inc-proc.f90"
#undef TYPEPARAM
end module
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…