通过更改makefile来覆盖FORTRAN和C.

1 c fortran makefile fortran-iso-c-binding

我有一个FORTRAN代码,它调用C例程来计算度量.FORTRAN代码是:

program fortran
implicit none
interface
double precision function fpli_hv(A, d, n)
real :: A(5,3)
integer :: d, n
end function fpli_hv
end interface
real :: A(5,3)
double precision :: HV
integer :: i, j
A(1,:) = (/1.1,3.2,2.0/)
A(2,:) = (/6.3,5.2,7.2/)
A(3,:) = (/3.3,4.4,9.1/)
A(4,:) = (/3.3,5.2,2.1/)
A(5,:) = (/7.6,1.7,4.3/)
HV = fpli_hv(A, 3, 5)
end program fortran  
Run Code Online (Sandbox Code Playgroud)

c函数看起来像这样:

double fpli_hv(double *front, int d, int n, double *ref);  
Run Code Online (Sandbox Code Playgroud)

为了俱乐部c和fortran,我需要在我的makefile中包含一个Makefil.lib.我这样做了,并按如下方式准备了我的makefile:

# The makefile should contain a set of suffix rules. All suffixes must
# be defined. In this case we will have .o for object files, .c for
# C files, and .f for Fortran files.
.SUFFIXES: .o .c .f90

# LIBRARY:
LIBHV = /gpfs0/home/shafiiha/programs/hv-2.0rc1-src/fpli_hv.a
#include Makefile.lib

# Define the C and Fortran compilers to be used in this makefile:
CC=
FC=gfortran -ffree-form -c

# Define flags to be used by the C and Fortran compilers:
CFLAGS =    
FFLAGS =

# Define include to be used by the C and Fortran compilers:
C_INCLUDES =     
F_INCLUDES = fortran.f90

# The linker executable in this case must be the MPI Fortran compiler
# to build a mixed C and Fortran MPI code:
LINK = gfortran

# Define values of parameters that appear in the source codes:
DEFINES =

# Define the list of object files for the linker. The linker will use
# those files to build the executable.
OBJECTS = fortran.o

# The rule that makes the drv executable (note that libraries have
# been specified by the mpif90 linker):
fortran: $(OBJECTS) 
    $(LINK) -o fortran $(OBJECTS) $(LIBHV)

# The rule that makes all object files from C sources:
.c.o:
    $(CC) $(CFLAGS) $(C_INCLUDES) $(DEFINES) $<

# The rule that makes all object files from Fortran sources:
.f90.o:
    $(FC)  $(FFLAGS)  $(F_INCLUDES) $^ $(LIBHV)

# The rule for deleting object files no longer needed after using
# make for drv:
clean:
    rm  *.o
Run Code Online (Sandbox Code Playgroud)

但是当我做到这一点时,我得到了这样的信息:

gfortran -o fortran fortran.o /gpfs0/home/shafiiha/programs/hv-2.0rc1-src/fpli_hv.a  
fortran.o: In function `MAIN__':  
fortran.f90:(.text+0x548): undefined reference to `fpli_hv_'  
collect2: ld returned 1 exit status  
make: *** [fortran] Error 1  
Run Code Online (Sandbox Code Playgroud)

你能帮我解释为什么我会收到这个错误吗?非常感谢.

M. *_* B. 5

在这个时代,从Fortran调用C的最佳方法是使用ISO C Binding.你的问题是Fortran默认做的名称,以避免与C或标准库的例程冲突,通常添加下划线.使用ISO C Binding,您既可以指定被调用例程的确切名称,也可以覆盖名称修改,并轻松地在参数上实现Fortran-C一致性.在Fortran端,您编写了一个描述C例程的接口.这里有以前的答案,gfortran手册中有一些例子.这些示例并非gfortran独有,因为ISO C Binding是Fortran 2003语言标准的一部分.