I’m using GNU Fortran (gfortran) to build several shared libraries, and then dynamically linking to them from a Fortran program. The process is a little different than what I’m used to for C libraries, so I thought I’d explain it. Unlike C, there is no need to #include header files when compiling code that relies on functions defined in an external library. Likewise, there is no need to use -l or -L linking flags to tell the linker about s hared libraries (at least when they’re in the same directory). In fact, the whole process requires a lot less command-line options than I had expected.
Building the Fortran shared libraries
I want to test a library called my_library. However, this library relies upon another library, which is called cfdrc_user_access. I want to compile a unit-test program that calls my library and makes sure it is working correctly.
gfortran -shared -fPIC -o cfdrc_user_access.so cfdrc_user_access.f90 gfortran -shared -fPIC -o cfdrc_user.so my_library.f90
Linking the shared libraries with a Fortran program
First, compile the program to an object file (.o), using the -c flag as shown on the first line. Then use gfortran to link the object file with the shared libraries created in the previous step:
gfortran -c blocking.f90 gfortran -o blocking blocking.o cfdrc_user.so cfdrc_user_access.so
Remember, unless the shared libraries are in a directory that’s already on your dynamic linker path, you will probably need to modify your LD_LIBRARY_PATH in order to run the program.
export LD_LIBRARY_PATH=/home/yourname/current_working_directory/ ./blocking
That worked for me–hopefully it helps you.
Thank you so much!!!!!!!!!!!! it really helped me! Greatly appreciate!
Thanks a lot!!!
Thanks a lot. It remained me how easy it was! 🙂
Pingback: Interface between Fortran77 program and Fortran90 program | Physics Forums
even though I updated LD_LIBRARY_PATH… gfortran looks in /usr/bin/ld….. I can not understand it…
I think you may be confused about what LD_LIBRARY_PATH does. It does NOT affect the behavior of GFortran during compiling or linking! LD_LIBRARY_PATH tells the Linux linker where to find shared libraries at RUNTIME. Please read this page to get a better overall understanding of how shared libraries work on Linux: https://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html