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.f90
gfortran -shared -fPIC -o 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

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/

That worked for me–hopefully it helps you.


3 thoughts on “Building and linking to a shared Fortran library

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s