使用gfortran和gcc从c访问fortran模块数据

cau*_*chy 5 c fortran fortran-iso-c-binding

我正在尝试访问fortran代码中的模块变量,从C调用它.我已经调用了一个子例程,但是无法调用变量.

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
Run Code Online (Sandbox Code Playgroud)

而C代码是

#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;
}
Run Code Online (Sandbox Code Playgroud)

我正在编译

gcc -c ccode.c
gfortran -c fortrancode.f90
gcc fortrancode.o ccode.o -lgfortran -o myprogram
Run Code Online (Sandbox Code Playgroud)

gcc以未定义的引用响应`aa'

jsp*_*jsp 8

我们看到使用objdump查看符号

0000000000000000 g     O .bss   000000000000000c __mymodule_MOD_aa
Run Code Online (Sandbox Code Playgroud)

您需要添加bind(C)到您的aa变量

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
Run Code Online (Sandbox Code Playgroud)

现在$ objdump -t fortrancode.o

000000000000000c       O *COM*  0000000000000004 aa
Run Code Online (Sandbox Code Playgroud)

#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;
}
Run Code Online (Sandbox Code Playgroud)

$ ./myprogram 
hello world from C
 hello world from Fortran 90
1.000000 2.000000 3.000000 
Run Code Online (Sandbox Code Playgroud)