user1407220 user1407220 - 1 year ago 113
C Question

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".

The FORTRAN routine (tt.f90) is:

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

A c++ caller (testcpp.cpp) code is

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

A fortran caller (testf.f90) code is

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

the makefile is

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
-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

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.

Any idea what I missing here??

Thanks a lot.

Note: the final fortran function will all be binary, so adjusting the fortran code (e.g. iso_c_binding) is not an option.

Answer Source

you have to specify the library after the object file which uses a symbol defined in it, i.e.,

g++ -o testcpp testcpp.o -L. -ltt -lgfortran
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download