Sample program: C/C++ calling Fortran
The following example illustrates how program units written in
different languages can be combined to create a single program. It
also demonstrates parameter passing between C/C++ and
Fortran subroutines with different data types as arguments. The example
includes the following source files:
- The main program source file: example.c
- The Fortran add function source file: add.f
Main program source file: example.c
#include <stdio.h>
extern double add(int *, double [], int *, double []);
double ar1[4]={1.0, 2.0, 3.0, 4.0};
double ar2[4]={5.0, 6.0, 7.0, 8.0};
main()
{
int x, y;
double z;
x = 3;
y = 3;
z = add(&x, ar1, &y, ar2); /* Call Fortran add routine */
/* Note: Fortran indexes arrays 1..n */
/* C indexes arrays 0..(n-1) */
printf("The sum of %1.0f and %1.0f is %2.0f \n",
ar1[x-1], ar2[y-1], z);
} Fortran add function source file: add.f
REAL*8 FUNCTION ADD (A, B, C, D)
REAL*8 B,D
INTEGER*4 A,C
DIMENSION B(4), D(4)
ADD = B(A) + D(C)
RETURN
END Compile the main program and Fortran add function source files
as follows:
xlc -c example.c
xlf -c add.f Link the object files from compile step to create executable add:
xlc -o add example.o add.oExecute binary:
./addThe output is as follows:
The sum of 3 and 7 is 10