使用 ifort 构建可执行共享库

Ing*_*ngo 5 fortran shared-libraries intel-fortran

有几个关于 SO 的精彩讨论已经涵盖了如何在 Linux 上生成可执行共享库:

在 C/C++ 中,这似乎相对简单;基本上有两个部分:

  1. 通过在库源代码中包含以下.interp内容,向 ELF添加一个部分(因为ld不包括共享库的部分):
    const char interp_section[] __attribute__((section(".interp"))) = "/path/to/dynamic/linker";
  2. 链接时设置适当的入口点,使用 -Wl,-e,entry_point

有谁知道如何使用 Fortran 编写的库来实现这一目标?具体来说,如何将一个.interp部分添加到使用编译的共享库中ifort

v-j*_*joe 5

借助 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 */
Run Code Online (Sandbox Code Playgroud)
! 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
Run Code Online (Sandbox Code Playgroud)
! linktest.f90: compile e.g. with ifort -c linktest.f90
! main Fortran program for testing

program linktest

call libroutine

end
Run Code Online (Sandbox Code Playgroud)

对于编译和链接:

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
Run Code Online (Sandbox Code Playgroud)

直接执行动态链接库./libtestif.so会调用execentry,并运行链接测试程序

LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH ./linktest
Run Code Online (Sandbox Code Playgroud)

将会通知libroutine

只需要 C 代码来创建该.interp部分。ld标志中的下划线-Wl,-e,execentry_是根据 Intel ifort(或 GNU gfortran)与 GNU 或 Intel C 编译器的符号名称修饰添加的。