mojijoon
mojijoon

Reputation: 129

linking fortran code to library

I'm trying to link my main code to a library

main code:

program main1
call test1
end program main1

library:

subroutine test1
print*,'ok'
end subroutine test1

then I create library :

gfortran -shared -fPIC -o lib1.so 1.f90

and compile main code

gfortran -c main.f90

and link

gfortran main.o lib1.so

but I've got this error :

./a.out: error while loading shared libraries: lib1.so: cannot open shared object file: No such file or directory

what am I doing wrong?

Upvotes: 1

Views: 2028

Answers (1)

chris-sc
chris-sc

Reputation: 1718

your example does work, but you are just missing a small thing: When using a shared library, your program (main.f90 / a.out) will try to find the linked library in one of the library folders (such as /lib*, /usr/lib* or /usr/local/lib*).

If you want to specify another folder for your shared library (for example for testing/debugging), you can use the enviroment variable LD_LIBRARY_PATH to "tell" linux another place to look for shared libraries.

So, assuming you wrote your program in the folder /home/mojijoon/fortran you can get the correct output after setting the library path by:

$: export LD_LIBRARY_PATH=LD_LIBRARY_PATH:/home/mojijoon/fortran
$: ./a.out
  ok

You can find more information on shared libraries (and the LD_LIBRARY_PATH enviromental variable) here: tldp.org - shared libraries

Upvotes: 2

Related Questions