Calling C function/subroutine in Fortran code

﹥>﹥吖頭↗ 提交于 2019-11-28 11:19:33

You need to provide an interface body for the C function inside the specification part of the Fortran main program that tells the Fortran compiler that the name addnums is a C function. Something like:

INTERFACE
  SUBROUTINE addnums(a, b) BIND(C)
    USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_INT
    IMPLICIT NONE
    INTEGER(C_INT) :: a, b
  END SUBROUTINE addnums
END INTERFACE

(With those compilers on that platform without special options the default kind of integer is the same as C_INT - but being explicit about the integer KIND helps protect you if compiler/platform or compile options change.)

c.anna

Here's two things I can see right off the bat (I work mainly with FORTRAN77 so this may not be the newest or best way to do this):

  1. Since your C function is, well, a function (and not a subroutine), you'll need to declare 'addnums' as EXTERNAL. Add this to your code in your declarations section.

    EXTERNAL addnums
  2. Add an underscore to the name of the function in your C code. FORTRAN does this automatically to its own functions, but not to functions in other languages. So, the function's signature would be

    void addnums_( int* a, int* b )

This page has a pretty good rundown on mixing C and FORTRAN. Hope this helped!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!