从c++调用FORTRAN库的问题

Problems calling FORTRAN library from c++

本文关键字:问题 FORTRAN c++ 调用      更新时间:2023-10-16

我在c++中调用FORTRAN子程序时遇到问题,当函数放入用" arrcs "创建的库中时。

FORTRAN例程(tt.f90)是:

Module A
contains
  Subroutine SubIF2(ii)
    Integer*8, Intent(In) :: ii
    write(*,*) "hello", ii
  End Subroutine SubIF2
End Module A

c++调用者(testcpp.cpp)的代码是

#include <iostream>
using namespace std;
extern"C" {
  void __a_MOD_subif2(long long int *ii);
}
main(){
  long long int ii=5;
  __a_MOD_subif2(&ii);
  return 0;
}

fortran调用者(testf.f90)的代码是

Program test
  use A
  integer*8 :: i=1
  call SubIF2(i)
End Program test

makefile是

p=/PathToMyWorkDirectory
all:
    gfortran -c tt.f90
    ar rcs libtt.a tt.o
    g++ -c testcpp.cpp
    gfortran -c testf.f90
    -gfortran -o testf90 testf.o tt.a
    -g++ tt.o testcpp.o -o testcpp -lgfortran
    -g++ -L$(p) -ltt testcpp.o -o testcpp -lgfortran
clean:
    -rm *.o *.mod
    -rm testf90
    -rm testcpp

而"gfortran -o testf90 testf. 90"o tt。和g++ tt。o testcpp。testcpp - lfortran"生成一个工作的可执行文件";0 - 0 testcpp - lfortran "崩溃

testcpp.o: In function `main':
testcpp.cpp:(.text+0x18): undefined reference to `__a_MOD_subif2'
collect2: error: ld returned 1 exit status

由于fortran可执行文件的链接工作,我看不出在库创建中有任何错误。

你知道我错过了什么吗?

谢谢你。

注意:最后的fortran函数都是二进制的,所以不能调整fortran代码(例如iso_c_binding)

您必须在使用其中定义的符号的对象文件之后指定库,即

g++ -o testcpp testcpp.o -L. -ltt -lgfortran