Using Modules in Fortran/C Mixed-Language Programming

Modules are the simplest way to exchange large groups of variables with C, because Intel Fortran modules are directly accessible from C/C++.

The following example declares a module in Fortran, then accesses its data from C:

Fortran code

 ! F90 Module definition     MODULE EXAMP        REAL A(3)        INTEGER I1, I2        CHARACTER(80) LINE        TYPE MYDATA           SEQUENCE           INTEGER N           CHARACTER(30) INFO        END TYPE MYDATA     END MODULE EXAMP

C code

  \* C code accessing module data *\
extern float examp_mp_a[3];
extern int examp_mp_i1, examp_mp_i2;
extern char examp_mp_line[80];  
extern struct {
           int n;
           char info[30];
} examp_mp_mydata;

When the C++ code resides in a .cpp file, C++ semantics are applied to external names, often resulting in linker errors. In this case, use the extern "C" syntax (see C/C++ Naming Conventions):

\* C code accessing module data in .cpp file*\
extern "C" float examp_mp_a[3];
extern "C" int examp_mp_i1, examp_mp_i2;
extern "C" char examp_mp_line[80];
extern "C" struct {
           int n;
           char info[30];
} examp_mp_mydata;

You can define an interface to a C routine in a module, then use it like you would an interface to a Fortran routine. The C code is:

   // C procedure  void pythagoras (float a, float b, float *c)  {      *c = (float) sqrt(a*a + b*b);  }

Using the same example when the C++ code resides in a .cpp file, use the extern "C" syntax (see C/C++ Naming Conventions):

  // C procedure  extern "C" void pythagoras (float a, float b, float *c)  {      *c = (float) sqrt(a*a + b*b);  }

The Fortran code to define the module CPROC:

   ! Fortran 95/90 Module including procedure      MODULE CPROC         INTERFACE            SUBROUTINE PYTHAGORAS (a, b, res)             !DEC$ ATTRIBUTES C :: PYTHAGORAS             !DEC$ ATTRIBUTES REFERENCE :: res  ! res is passed by REFERENCE because its individual attribute  ! overrides the subroutine's C attribute               REAL a, b, res  ! a and b have the VALUE attribute by default because  ! the subroutine has the C attribute            END SUBROUTINE         END INTERFACE      END MODULE

The Fortran code to call this routine using the module CPROC:

   ! Fortran 95/90 Module including procedure      USE CPROC         CALL PYTHAGORAS (3.0, 4.0, X)         TYPE *,X      END