Calling C function/subroutine in Fortran code

后端 未结 2 1011
滥情空心
滥情空心 2020-12-10 15:05

I am attempting to compile and link a Fortran code calling c subroutine:

Fortran code:

program adder
integer a,b
a=1
b=2
call addnums(a,b)
stop    
e         


        
相关标签:
2条回答
  • 2020-12-10 15:28

    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!

    0 讨论(0)
  • 2020-12-10 15:44

    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.)

    0 讨论(0)
提交回复
热议问题