Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access fortran module data from c using gfortran and gcc

I'm trying to access module variables in a fortran code, calling it from C. I already call a subroutine, but cannot call the variables.

module myModule
use iso_c_binding
implicit none
real(C_FLOAT) aa(3)
contains
subroutine fortranFunction() bind(C)

print *,"hello world from Fortran 90"
aa(1)=1.0;
aa(2)=2.0;
aa(3)=3.0;

end subroutine

end module

and the C code is

#include "stdio.h"

extern void fortranfunction();
extern float mymodule_aa_[3];

int main()
{
printf("hello world from C\n");
fortranfunction();

printf("%f %f %f \n",aa[0],aa[1],aa[2]);
return 0;
}

I'm compiling via

gcc -c ccode.c
gfortran -c fortrancode.f90
gcc fortrancode.o ccode.o -lgfortran -o myprogram

to which the gcc responds with undefined reference to `aa'

like image 266
cauchi Avatar asked Jul 26 '13 16:07

cauchi


1 Answers

Using objdump to look at the symbols, we see

0000000000000000 g     O .bss   000000000000000c __mymodule_MOD_aa

You need to add bind(C) to your aa variable

module myModule
use iso_c_binding
implicit none
real(C_FLOAT), bind(C) :: aa(3)
contains
subroutine fortranFunction() bind(C)

print *,"hello world from Fortran 90"
aa(1)=1.0;
aa(2)=2.0;
aa(3)=3.0;

end subroutine

end module

now $ objdump -t fortrancode.o says

000000000000000c       O *COM*  0000000000000004 aa

and

#include "stdio.h"

extern void fortranfunction();
extern float aa[3];

int main()
{
printf("hello world from C\n");
fortranfunction();

printf("%f %f %f \n",aa[0],aa[1],aa[2]);
return 0;
}

and

$ ./myprogram 
hello world from C
 hello world from Fortran 90
1.000000 2.000000 3.000000 
like image 92
jsp Avatar answered Oct 20 '22 07:10

jsp