Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 526
mle0312 Avatar asked Jan 18 '26 09:01

mle0312


1 Answers

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

like image 134
Oo.oO Avatar answered Jan 21 '26 07:01

Oo.oO