Assume now for some reason I can only have a file(Fortran code contained), named "inc.f90", to be used by 'include' statement in other f90 files. When I use this code in the other file, say "use.f90", I type "include 'inc.f90'". But in this case, there is path information contained in "use.f90". Then I need to organize my code files in a fixed way. For example, if I move "inc.f90" into other position("other/path/inc.f90"), I need to change the source code in "use.f90" accordingly. This is awkward! I wonder if I can use some trick to pack "inc.f90" into a module, after which I need only to tell where all files are to the compiler.
Asked
Active
Viewed 296 times
0
-
So in "use.f90", I can fix " INCLUDE 'inc.f90' " ? – hengyue li Dec 24 '17 at 05:08
1 Answers
0
If you are using gfortran
, I guess you can use the -I
option to specify the search path for included files. For example, if we have the following main.f90
in the current directory,
$ cat ./main.f90
module testmod
implicit none
contains
include "inc1.f90"
include "inc2.f90"
end
program main
use testmod
call sub1 !! defined in inc1.f90
call sub2 !! defined in inc2.f90
end
and sub1.f90 and sub2.f90 in libdir/sub1 and libdir/sub2, respectively,
$ ls libdir/*
libdir/sub1:
./ ../ inc1.f90
libdir/sub2:
./ ../ inc2.f90
with
$ cat libdir/sub1/inc1.f90
subroutine sub1
print *, "hello1"
end
$ cat libdir/sub2/inc2.f90
subroutine sub2
print *, "hello2"
end
we can compile them as
$ gfortran -Ilibdir/sub1 -Ilibdir/sub2 main.f90
According to man gfortran
, there are some related options (-idirafter
for alternative search directories and -J
for .mod files), which may also be useful. I guess we have similar options for other compilers as well.

roygvib
- 7,218
- 2
- 19
- 36
-
Great! This solved my problem. For personal interest, however, I wonder if we can have a general way to pack a piece of fragmentary code into a module? – hengyue li Dec 24 '17 at 05:58
-
Actually, that part is what I still cannot understand the precise goal (particularly, the meaning of "pack"). Maybe another question with more detailed intent/goal may be worth trying..? (because other people may have some idea.) – roygvib Dec 24 '17 at 06:01
-
FYI, in my case, I separate various subroutines into different files, and "include" all of them into a single module (according to its computational purpose). This way, I can avoid reading a very long module file :) – roygvib Dec 24 '17 at 06:04
-
Never mind. I just wondering if we can use a module to reproduce all the function of "include". Something like, I do not know, maybe we can save all the code into a string? Personally, I would like to manage all my code in module format. But it seems impossible? The goal of using 'include' is to solve the problem like this:https://stackoverflow.com/questions/44860277/how-to-get-a-module-with-different-type-for-code-reuse/44860671#44860671 – hengyue li Dec 24 '17 at 08:03