【问题标题】:access fortran module data from c using gfortran and gcc使用 gfortran 和 gcc 从 c 访问 fortran 模块数据
【发布时间】:2013-07-26 16:51:01
【问题描述】:

我正在尝试访问 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

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

我正在编译通过

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

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

【问题讨论】:

  • aa 是如何传递的?

标签: c fortran fortran-iso-c-binding


【解决方案1】:

使用objdump查看符号,我们看到了

0000000000000000 g     O .bss   000000000000000c __mymodule_MOD_aa

您需要将 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

现在$ objdump -t fortrancode.o

000000000000000c       O *COM*  0000000000000004 aa

#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;
}

$ ./myprogram 
hello world from C
 hello world from Fortran 90
1.000000 2.000000 3.000000 

【讨论】:

    猜你喜欢
    • 2016-04-28
    • 2021-04-21
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    相关资源
    最近更新 更多