Calling a Fortran function in C



Since Slatec functions are written in Fortran, we need to know how to call a Fortran function in C. Suppose we have the simple Fortran function below, and we wish to use it from a C program.

C*** File: twice.f
C  Compile me to an object file.
C  Try:  f77 -c twice.f 	
       DOUBLE PRECISION FUNCTION TWICE(X)
C*** Comment		
C*** Return 2*argument	
        DOUBLE PRECISION X, Y	
        Y=2.0	
        TWICE=Y*X	
        RETURN 	
      END	
C THE END
					

We compile this into the object file twice.o:
f77 -c twice.f

Note: It is important to know that the Fortran compiler (unlike C) is sensitive to the spacing in the formatting; be aware that you need to replicate the spacing above.


Then we may use the Fortran function twice in a C program, as in the example at the bottom of this page.

Note that the argument to a Fortran function is always an address to a variable. Unlike C, Fortran's functions do not call by value.

The example below suggests two possiblities for callling conventions which may differ for your compiler--one is without underbar and the other (commented out) with an appended underbar; our current version of xlC (AIX) uses no underbars; older versions may use an underbar.

You must determine the calling convention of your compiler. You can either (try to) reference the manual, or just try compiling the program below (and linking it to twice.o) and see it it works:
% f77 -c twice.f
% cc calltwice.c twice.o
% a.out

Hopefully it worked. If not, try the commented version of main() below, and you may have better luck.

/* file: calltwice.c 						*/

#include 

/*   Some compilers may need prototyping; some don't.  		*/

double twice(double*);

int main() {
 double x,y;
 x=2.0;
 y=twice(&x);
 printf("Two times two is %g .\n",y);
 return 0;
}

/** Some compilers may have a different calling convention:	**
***
*** for example, an underbar.
*
* int main() {
*  double x,y;
*  x=2.0;
*  y=twice_(&x);
*  printf("Two times two is %g .\n",y);
*  return 0;
* }								*/


Summary:

Fortran functions's parameters are always addresses.

You need to determine if your C compiler uses any different form of calling a compiled Fortran functions than it does to call a compiled C function (calling convention).



Back to Main