在 C 编译器的帮助下创建一个附加的目标文件以链接到动态库,这样一个 Fortran90 可执行文件和动态链接库可以被创建:
/* stub.c: compile e.g. with gcc -c stub.c
const char dl_loader[] __attribute__((section(".interp"))) =
"/lib64/ld-linux-x86-64.so.2";
/* adjust string if path or architecture is different */
! testif.f90: compile e.g. with ifort -c -fPIC testif.f90
subroutine execentry
write(*,*) 'Written from executable.'
! without call to exit seems to lead to segmentation fault
call exit(0)
end subroutine
subroutine libroutine
write(*,*) 'Written by libroutine.'
end subroutine
! linktest.f90: compile e.g. with ifort -c linktest.f90
! main Fortran program for testing
program linktest
call libroutine
end
用于编译和链接:
gcc -c stub.c
ifort -c -fPIC testif.f90
ifort -c linktest.f90
ifort -shared -o libtestif.so testif.o stub.o -Wl,-e,execentry_
ifort -o linktest linktest.o -L. -ltestif
直接执行动态链接库./libtestif.so会调用execentry,并运行链接测试程序
LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH ./linktest
将致电libroutine。
仅需要 C 代码来创建 .interp 部分。 ld 标志 -Wl,-e,execentry_ 中的下划线是根据 Intel ifort(或 GNU gfortran)与 GNU 或 Intel C 编译器的符号名称修改添加的。