简体   繁体   English

从C ++调用FORTRAN库的问题

[英]Problems calling FORTRAN library from c++

I experience problems calling a FORTRAN subroutine from C++ when the function is put into a library created with "ar rcs". 将函数放入使用“ ar rcs”创建的库时,从C ++调用FORTRAN子例程时遇到问题。

The FORTRAN routine (tt.f90) is: FORTRAN例程(tt.f90)是:

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

A c++ caller (testcpp.cpp) code is 一个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;
}

A fortran caller (testf.f90) code is fortran调用者(testf.f90)代码为

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

the makefile is 该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

While the "gfortran -o testf90 testf.o tt.a" and "g++ tt.o testcpp.o -o testcpp -lgfortran" yield a working executable, "g++ -L$(p) -ltt testcpp.o -o testcpp -lgfortran" crashes 尽管“ gfortran -o testf90 testf.o tt.a”和“ g ++ tt.o testcpp.o -o testcpp -lgfortran”会生成一个可运行的可执行文件,而“ g ++ -L $(p)-ltt testcpp.o -o testcpp -lgfortran”崩溃

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

Since linking works for the fortran executable, I cannot see anything wrong in the library creation. 由于链接适用于fortran可执行文件,因此在库创建中我看不到任何错误。

Any idea what I missing here?? 知道我在这里错过了什么吗?

Thanks a lot. 非常感谢。

Note: the final fortran function will all be binary, so adjusting the fortran code (eg iso_c_binding) is not an option. 注意:最终的fortran函数将全部为二进制,因此不能选择调整fortran代码(例如iso_c_binding)。

您必须在目标文件后指定使用该库中定义的符号的库,即

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM