Building and linking to a shared Fortran library
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.f90Linking 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.soRemember, 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/
./blockingThat worked for me–hopefully it helps you.
Comments
Comment #1 by Aboulghasem
Aboulghasem - Nov 4, 2011
Thank you so much!!!!!!!!!!!! it really helped me! Greatly appreciate!
Comment #2 by malaguita
malaguita - Feb 4, 2014
Thanks a lot!!!
Comment #3 by Phorious
Phorious - Jun 3, 2015
Thanks a lot. It remained me how easy it was! :-)
Comment #4 by Interface between Fortran77 program and Fortran90 program | Physics Forums
Interface between Fortran77 program and Fortran90 program | Physics Forums - Oct 3, 2018
[…] http://astroa.physics.metu.edu.tr/M...ojects/bldaps_for/ug1l_create_shared_libs.htm https://shocksolution.com/2009/10/26/building-and-linking-to-a-shared-fortran-library/ jedishrfu, Oct 3, 2018 at 9:52 […]
Comment #5 by Manisha
Manisha - Jun 4, 2020
even though I updated LD_LIBRARY_PATH… gfortran looks in /usr/bin/ld….. I can not understand it…
Comment #6 by craig
craig - Jun 4, 2020
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