2013-10-13 51 views
1

我想在C使用FORTRAN模块子程序,不能打通使用FORTRAN模块子程序,这里是我的问题的简化版本:如何在C

我有一个包含一个子程序一个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 to某人

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

+0

这是一个相关的问题:http://stackoverflow.com/questions/15557439/how-to-call-a-fortran90-function-included-in-a-module-in-c-code – Jason

回答

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库中带来的。

+0

它的工作原理。非常感谢!你知道如何使用英特尔编译器做同样的事情吗?我总是得到错误与英特尔:main.o:在函数'主 ': 的main.c :(文字+为0x0):'主要的多个定义':/导出/用户/ nbtester/efi2linux_nightly /支 for_main.o -13_0/20120801_000000/libdev/FRTL/SRC/libfor/for_main.c :(文本+为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

+2

@xslittlegrass,如果使用'ifort'将Fortran代码与C/C++'main()'函数链接起来,则应该给它一个'-nofor-main'选项,否则编译器会链接'for_main.o'目标文件,它包含一个'main'函数,后者又调用主Fortran程序(通常在引擎盖下命名为MAIN)。 –

+0

@HristoIliev它的工作原理!谢谢。请问icc的编译器标志是什么,要求icc将Fortran库引入? – xslittlegrass

1

的原因您的链接错误是双重的:

  • 你省略用于保存从最后的命令行(md.o)模块的源文件中的目标文件。

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

修复这些问题,你就可以去吧。