【问题标题】:Calling a subroutine in a module from C从 C 调用模块中的子例程
【发布时间】:2016-05-29 17:07:20
【问题描述】:

我想知道如何让 C 程序调用 Fortran 90 模块中包含的 Fortran 90 子例程。

This question deals with a similar problem,我正在尝试实施解决方案,但我仍然遇到问题。

以下是包含主函数的testC.c 文件和包含Fortran 90 子例程的模块文件testF.f90 的玩具示例。

testC.c

#include <stdlib.h>
#include <stdio.h>

extern void __testF_MOD_fortfunc(int *,float *);

int main() {
   int ii=5;
   float ff=5.5;

   __testF_MOD_fortfunc(&ii, &ff);

   return 0;
}

testF.f90

module testF

contains

subroutine fortfunc(ii,ff)
    implicit none

    integer ii
    real*4  ff

    write(6,100) ii, ff
    100 format('ii=',i2,' ff=',f6.3)

    return
end subroutine fortfunc

end module testF

要编译,我使用以下几行

gcc -c testC.c
gfortran -o testF.f90
gcc -o test testF.o testC.o -lgfortran

我收到错误消息

testC.o: In function `main':
testC.c:(.text+0x27): undefined reference to `__testF_MOD_fortfunc'
collect2: error: ld returned 1 exit status

【问题讨论】:

  • 我已更新我的问题以更具体地说明问题。即,它在编译时失败,并说“对 __testF_MOD_fortfunc 的未定义引用
  • 文件列出的顺序对链接器很重要。在链接命令中交换 testC.o 和 testF.o 可能会解决您的问题。
  • 尝试交换 testC.o 和 testF.o。不幸的是,没有运气。
  • 仅供参考:您不需要将函数声明指定为“extern”。 AFAIK 它仅可用于变量。
  • 请使用通用标签fortran。否则,您指的是超过 25 年的特定标准(提示:最新发布的标准是 Fortran 2008,Fortran 2015 正在开发中)。作为一个额外的好处,更多的用户正在关注通用标签。

标签: c module fortran


【解决方案1】:

您可以使用objdump -t testF.o 直接从对象中读出函数名称。这揭示了以下行:

0000000000000000 g     F .text  00000000000000b4 __testf_MOD_fortfunc

这是你的函数名。你可以看到它是小写的testf。 在 C 代码中使用它应该可以解决您的问题。

但是,这些命名约定取决于编译器。你真的应该看看ISO_C_binding 模块和现代 Fortran 改进的 C 互操作性。

【讨论】:

    猜你喜欢
    • 2011-02-17
    • 2016-06-05
    • 2014-01-14
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多