pengfukai 发表于 2015-11-30 15:44:09

C Fortran 混合编程

我在使用C,Fortran混合编程时遇到如下问题:fmain.obj : error LNK2019: unresolved external symbol _addnumber referenced in function _MAIN__,各位大侠知道该怎么解决吗?
我的Fortran代码为:

    program fmain
    use,intrinsic:: iso_c_binding
    implicit none
    interface
      subroutine AddNumber(res,num) bind(C)
      use,intrinsic:: iso_c_binding,only: C_INT, C_DOUBLE
      implicit none
      real(kind=C_DOUBLE):: res
      integer(kind=C_INT):: num
      end subroutine AddNumber
    end interface
    integer(kind=4):: num
    real(kind=8):: res
    res=0d0
    do while(.true.)
      write(*,*) 'please input a integral number:'
      read(*,*) num
      call AddNumber(res,num)
      write(*,'(A,3X,F10.3)') 'The result is:',res
    enddo
    end program fmainC代码为:
#include <stdio.h>
extern "C" void AddNumber(double res, int num)
{
      res=res+num;
}
操作系统是64位windows 7, 编译器是vs2010+intel visual fortran XE 2013


fcode 发表于 2015-11-30 18:08:58

解决方案管理器,截图。

pasuka 发表于 2015-11-30 18:19:28

修改了一下,gcc编译无问题,至于为啥这么改,ivf的帮助文档有详细的混合编程说明
首先得明白,传址、传值
Fortran代码
program fmain
use, intrinsic:: iso_c_binding
implicit none
interface
        subroutine addnum(a, b) bind(c, name="AddNumber")
        import
        implicit none
        type(c_ptr),value::a
        integer(c_int),value, intent(in)::b
        end subroutine
end interface
integer(c_int):: num
real(c_double),target:: res
num = 2
res = 1.0D0
call addnum(c_loc(res), num)
write(*, *)"Result:",res
end program
C代码
#include <stdio.h>

void AddNumber(double *res, int num)
{
        printf("C\tInput:%f\n", *res);
        *res += (double)num;
        printf("C\tAdded:%f\n", *res);
}

pengfukai 发表于 2015-11-30 18:36:22

pasuka 发表于 2015-11-30 18:19
修改了一下,gcc编译无问题,至于为啥这么改,ivf的帮助文档有详细的混合编程说明
首先得明白,传址、传值
...

谢谢你的解答,找了一晚上,终于找到了解决方法。
https://software.intel.com/en-us/forums/intel-visual-fortran-compiler-for-windows/topic/326037

pengfukai 发表于 2015-11-30 19:13:03

pasuka 发表于 2015-11-30 18:19
修改了一下,gcc编译无问题,至于为啥这么改,ivf的帮助文档有详细的混合编程说明
首先得明白,传址、传值
...

还想问你一个问题,就是bind(C,Name='')中Name表示的名字必须与C文件里的函数名一致是吗?与Fortran的函数名也必须一致还是可以不同呢?

fcode 发表于 2015-11-30 19:26:36

与C的一致就行。不必与Fortran的函数名一致。(否则的话就没意思了,重复的名字连着写两次)

pengfukai 发表于 2015-12-1 06:53:54

fcode 发表于 2015-11-30 19:26
与C的一致就行。不必与Fortran的函数名一致。(否则的话就没意思了,重复的名字连着写两次) ...

知道啦,谢谢~
页: [1]
查看完整版本: C Fortran 混合编程