Reputation: 943
I am working on a Fortran library that contains many different functions. To develop it and maintain it more easily, I have divided this library into several modules (e.g., part1.f90
, part2.f90
, part3.f90
) and a main module mylib.f90
using all these individual modules:
module mylib
use part1
use part2
use part3
implicit none
end module mylib
The idea is then to use this main module in my programs with use mylib
. I am however having trouble compiling and linking these modules.
The modules are all contained and compiled in a directory /mylib/src/
, which therefore also contains the corresponding *.o
and *.mod
files. When I compile my program in a different directory using:
gfortran -I/mylib/src myprog.f90 -o myprog
I would expect the compiler to find the required modules in the specified directory. But unfortunately, I get an error message that there are undefined references to functions that are actually contained in the submodules.
What am I doing wrong here?
Thank you for your help!
Upvotes: 0
Views: 1822
Reputation: 943
I have found some information from other websites, see for instance: http://fortranwiki.org/fortran/show/Library+distribution
The first approach would be to compile the modules, save the *.mod
files in a specific directory, e.g. /usr/lib/fortran
, and create an archive libmylib.a
containing the *.o
files using ar -r libmylib.a *.o
. Then, to compile my program I would add the flag -I/usr/lib/fortran
to indicate the compiler where the modules are, so that he can find them when he encounters a use mylib
in my code. finally, I would link my program against the archived library using the flag -lmylib
, and indicating where the archived library is located with -L
.
The problem with this approach is that Fortran compiled modules are compiler-dependent, which implies that we have to be careful if using different compilers or even different versions of the same compiler on a machine.
The second approach would be to include the modules of the library in the build directory, and compile them together with the program.
Any other suggestions are welcome!
Upvotes: 0
Reputation: 78316
I think that you are omitting the linking of the object files in which the executable representation of your module functions (etc) are to be found. With the -I
option you're telling the compiler where to find the include files (ie the .mod
files) but nowhere are you telling it to link the .o
files that you have, I presume, already created. A simple way to link them would be to edit your compile command along the following lines:
gfortran -I/mylib/src -o myprog myprog.f90 /mylib/src/part1.o /mylib/src/part2.o ...
I expect that if I used the command-line for compiling (I don't, I use make
or some other build system) I'd know how to specify the path to the .o
files only once. Someone will probably come by here sooner or later and put us both in that particular picture, or you could break into the documentation.
Upvotes: 3