Help Files: Fortran77: Linking to C Procedures





     HELP                      June 15, 1985             F77/LINK_TO_C



                          Linking to C Procedures

     C is a commonly used programming language in UNIX.   "A  Portable
     Fortran   77   Compiler"  gives  complete  specification  of  the
     C/Fortran interface.  This help file summarizes  the  basics  for
     simple cases and gives a simple example.

     The following table from that paper lists  corresponding  Fortran
     and C declarations:

             Fortran                 C
             -----------             ---------
             integer*2 x             short int x;
             integer x               long int x;
             logical x               long int x;
             real x                  float x;
             double precision x      double x;
             complex x               struct { float r, i; } x;
             double complex x        struct { double dr, di; } x;
             character*6 x           char x[6];


     The following Fortran statements calls a  procedure  fill()  that
     sets the first 10 elements of ix() to the value 20:

                     integer ix(100)
             c
                     call fill(ix, 10,  20)

     In creating external symbols  for  subprogram  and  common  block
     names,  f77  adds  an underscore before and after external names,
     while the C compiler only adds an  underscore  before  the  name.
     Thus  the  C name fill_() corresponds to the f77 name fill(); and
     the corresponding C procedure is:

             fill_( vec, nvec, val)
             long *vec, *nvec, *val;
             {
                     long nv = *nvec;

                     while (nv-- > 0) *vec++ = *val;
             }

     Since Fortran passes variables by address, the C procedure treats
     the  parameters  as  pointers.   This also means that a temporary
     must be used.  If a temporary is not used, as in:

             while ((*nvec)-- > 0) *vec++ = *val;

     the value of the third parameter in the call would be destroyed.

     When mixing C and Fortran, it is simplist if all I/O is  done  in
     either  one  language or the other.  If I/O must be done in both,
     it is best to use a Fortran main program to make sure the f77 I/O
     library  is  properly initialized.  Otherwise, call 'f_init()' in
     the Fortran I/O library to initialize units 0, 5, and 6 to  stan-
     dard error, standard input and standard output and to line-buffer
     standard error.


Comments to decf@euler.berkeley.edu
© 1998 UC Regents