mle0312
mle0312

Reputation: 425

Linking library syntax with gfortran

In C++, if I want to do a custom compile (meaning to link additional libraries), I usually do the following:

g++ filename -o outputname -I/include_libraries_here -L/link_libraries_here -rpath=path_for_dynamic_linking_here 

How would I go about to do a similar thing using gfortran. I tried:

gfortran filename -o outputname -I/include_libraries_here -L/link_libraries_here -rpath=path_for_dynamic_linking_here 

So far, the syntax -I and -L work, suggesting that I managed to link and include the libraries. However, it seems that gfortran does not recognize rpath as a valid command.

Please let me know and thank you.

Upvotes: 3

Views: 11624

Answers (2)

CKE
CKE

Reputation: 1608

In addition to the accepted answer, please be aware of the following behavior of the gcc linker

As the gcc linker parses the command line only once from left to right, the order of the depending source and library files really matters. As hello.f90 uses a function defined in libfun, it must be placed before the library.

Hence the linking shall be done like this:

# without -rpath
gfortran -fno-underscoring -o hello -L. hello.f90 -lfun 
# in this case you have to make sure libfun.so is in LD_LIBRARY_PATH

# with rpath
gfortran -fno-underscoring -o hello -L. -Wl,-rpath=`pwd` hello.f90 -lfun 
# in this case, library will be properly located at runtime

Tested with gcc version gcc (Debian 10.2.1-6) 10.2.1 20210110.

More information regarding gcc linker invokation could be found here.

Upvotes: 0

Oo.oO
Oo.oO

Reputation: 13425

You don't have to use rpath during linking. Of course, you can.

Take a look here:

#include <stdio.h>

void fun() {
  printf("Hello from C\n");
}

we can create shared lib like this:

gcc -fPIC -shared -o libfun.so fun.c

Then, we can compile following code:

program hello
  print *, "Hello World!"
  call fun()
end program hello

like this:

# without -rpath
gfortran -fno-underscoring -o hello -L. -lfun hello.f90
# in this case you have to make sure libfun.so is in LD_LIBRARY_PATH

# with rpath
gfortran -fno-underscoring -o hello -L. -Wl,-rpath=`pwd` -lfun hello.f90
# in this case, library will be properly located at runtime

This will allow calling function from shared lib

./hello
 Hello World!
Hello from C

-rpath is ld's argument

-rpath=dir
           Add a directory to the runtime library search path.  This is used when linking an ELF executable with shared objects.  All -rpath arguments are concatenated
           and passed to the runtime linker, which uses them to locate shared objects at runtime.

Useful link:

http://www.yolinux.com/TUTORIALS/LinuxTutorialMixingFortranAndC.html

Upvotes: 3

Related Questions