Fortran Calls to C

OverviewHow Do I

This article applies the principles in Mixed-Language Issues to a typical case involving one function call and one subroutine call from Fortran to C. Default conventions are assumed for C, so adjustments are made to the Fortran code. The example in this article is the converse of that in C Calls to Fortran.

The Fortran main program uses the C attribute to call the C functions with the correct calling convention. The C attribute causes Fortran to generate all-lowercase names, so the ALIAS attribute must be used to preserve mixed case. Finally, pass by value and pass by reference are specified explicitly, though pass by value would have been assumed because of the C attribute.

C   File FORMAIN.FOR
C
      INTERFACE TO INTEGER*4 FUNCTION Fact [C,ALIAS:'_Fact'] (n)
      INTEGER*4 n [VALUE]
      END

      INTERFACE TO SUBROUTINE Pythagoras [C,ALIAS:'_Pythagoras'] (a,b,c)
      REAL*4 a [VALUE]
      REAL*4 b [VALUE]
      REAL*4 c [REFERENCE]
      END

      INTEGER*4 Fact
      REAL*4 c
      WRITE (*,*) 'Factorial of 7 is ', Fact (7)
      CALL Pythagoras (30, 40, c)
      WRITE (*,*) 'Hypotenuse if sides 30, 40 is ', c
      END

/*  File CSUBS.C  */

#include <math.h>

int Fact( int n )
{
    if (n > 1)
        return( n * Fact( n - 1 ));
    return 1;
}

void Pythagoras( float a, float b, float *c)
{
    *c = sqrt( a * a + b * b );
}