2

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

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

//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'

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

4

2 回答 2

3
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 库。

于 2013-10-13T04:09:33.840 回答
1

链接错误的原因有两个:

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

  • 您已经在 C++ 代码中调用sq了 fortran 。sb

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

于 2013-10-13T06:25:08.333 回答