Mixing C and Fortran Overview

This section discusses implementation-specific ways to call C procedures from a Fortran program.

Naming Conventions

By default, the Fortran compiler converts function and subprogram names to lower case, and adds a trailing underscore. The C compiler never performs case conversion. A C procedure called from a Fortran program must, therefore, be named using the appropriate case. For example, consider the following calls:

CALL PROCNAME()

The C procedure must be named procname_.

x=fnname()

The C procedure must be named fnname_.

In the first call, any value returned by procname is ignored. In the second call to a function, fnname must return a value.

Passing Arguments between Fortran and C Procedures

By default, Fortran subprograms pass arguments by reference; that is, they pass a pointer to each actual argument rather than the value of the argument. C programs, however, pass arguments by value. Consider the following:

Using Fortran Common Blocks from C

When C code needs to use a common block declared in Fortran, an underscore (_) must be appended to its name, see below.

Fortran code
common /cblock/ a(100)   real a
 

C code
struct acstruct {     
float a[100];    
};
extern struct acstruct cblock_;

Example

This example demonstrates defining a COMMON block in Fortran for Linux, and accessing the values from C.

Fortran code

COMMON /MYCOM/ A, B(100),I,C(10)
   REAL(4) A
   REAL(8) B
   INTEGER(4) I
   COMPLEX(4) C
   A = 1.0
   B = 2.0D0
   I = 4
   C = (1.0,2.0)
   CALL GETVAL()
   END
 

C code

typedef struct compl  complex;
struct compl{
   float real;
   float imag;
   };

extern struct {
          float a;
          double b[100];
          int i;
          complex c[10];
          } mycom_;

void getval_(){
printf("a = %f\n",mycom_.a);
printf("b[0] = %f\n",mycom_.b[0]);
printf("i = %d\n",mycom_.i);
printf("c[1].real = %f\n",mycom_.c[1].real);
}

penfold%  ifc common.o getval.o -o common.exe
penfold%  common.exe
a = 1.000000
b[0] = 2.000000
i = 4
c[1].real = 1.000000