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.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.

6 thoughts on “Building and linking to a shared Fortran library”

  1. Pingback: Interface between Fortran77 program and Fortran90 program | Physics Forums

  2. even though I updated LD_LIBRARY_PATH… gfortran looks in /usr/bin/ld….. I can not understand it…

Leave a Reply to Phorious Cancel Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.