【问题标题】:How to use fortran module subroutine in c如何在c中使用fortran模块子例程
【发布时间】:2013-10-13 03:36:16
【问题描述】:

我正在尝试在 c 中使用 fortran 模块子例程,但无法通过,这是我的问题的简化版本:

我有一个包含子例程的 fortran 模块,第二个子例程使用该模块。

!md.f90
module myadd
implicit none
contains

subroutine add1(a) bind(c)
implicit none
integer a
a=a+1

end subroutine add1
end module myadd


!sb.f90
subroutine sq(a) bind(c)
use myadd
implicit none
integer a
call add1(a)
a=a*a
end subroutine sq

现在我想在c中调用sb函数:

//main.cpp
extern "C"{ void sb(int * a); }
int main(){
  int a=2;
  sb(&a);
}

我应该如何将它们链接在一起?

我尝试了类似的东西

ifort -c md.f90 sb.f90
icc sb.o main.cpp

但它给出了错误

sb.o:在函数sq': sb.f90:(.text+0x6): undefined reference to add1' /tmp/icc40D9n7.o:在函数main': main.cpp:(.text+0x2e): undefined reference tosb'

有人知道如何解决这个问题吗?

【问题讨论】:

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


【解决方案1】:
int main(void){
  int a=2;
  sb(&a);
  return 0;
}

module myadd
use iso_c_binding
implicit none
contains

subroutine add1(a) bind(c)
implicit none
integer (c_int),intent (inout) :: a
a=a+1

end subroutine add1
end module myadd


!sb.f90
subroutine sq(a) bind(c, name="sb")
use iso_c_binding
use myadd
implicit none
integer (c_int), intent(inout) :: a
call add1(a)
a=a*a
end subroutine sq

gcc -c main.c
gfortran-debug fort_subs.f90 main.o

与 Fortran 编译器的链接更容易,因为它引入了 Fortran 库。

【讨论】:

  • 它有效。非常感谢!你知道如何使用英特尔编译器来做同样的事情吗?我总是收到英特尔错误:main.o: In function main': main.c:(.text+0x0): multiple definition of main' for_main.o:/export/users/nbtester/efi2linux_nightly/branch-13_0/20120801_000000/libdev/frtl/src/libfor/for_main.c:( .text+0x0):这里首先定义/home/compilers/Intel/composer_xe_2013.0.079/compiler/lib/intel64/for_main.o:在函数main': /export/users/nbtester/efi2linux_nightly/branch-13_0/20120801_000000/libdev/frtl/src/libfor/for_main.c:(.text+0x38): undefined reference to MAIN__'
  • @xslittlegrass,如果你使用 ifort 将 Fortran 代码与 C/C++ main() 函数链接,你应该给它 -nofor-main 选项,否则编译器链接 for_main.o 对象文件,其中包含一个 main 函数,该函数又调用主 Fortran 程序(通常在后台命名为 MAIN)。
  • @HristoIliev 它有效!谢谢。 icc 要求 icc 引入 fortran 库的编译器标志是什么?
  • @xslittlegrass,我不知道这样的选项。最好使用ifort 链接混合语言应用程序。
【解决方案2】:

链接错误的原因有两个:

  • 您从最终命令行 (md.o) 中省略了包含模块的源文件的目标文件。

  • 您在 C++ 代码中的 fortran 中调用了 sq sb

修好这些,你就可以走了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 2014-01-14
    • 2012-01-02
    • 2015-11-18
    相关资源
    最近更新 更多