Calling C from FORTRAN under Unix

Alex Martelli martelli at cadlab.sublink.ORG
Sun May 19 07:19:29 AEST 1991


packer at amarna.gsfc.nasa.gov (Charles Packer) writes:
:On a Unix system I want to call a C routine from a FORTRAN
:program. The linker says the C routine is undefined.  On a VMS
:system, the problem doesn't happen. The reason why there is a
:problem on a Unix system has something to do with the name of
:the C subroutine acquiring a preceding underscore ("_") during
:compilation, or some such nonsense. To anyone familiar with this
:problem: what is the way around it? 
My approach (simplistic compared to others'): C files defining
routines to be called from Fortran include this header file:

#if DECMIPS || IBM6150 || SUN3 || SUN4 || SONY || GREENHILLS
#   define __EXTRA_UNDERLINE        1
#endif
#define FTNLOG(logi)    -(!!(logi))     /* C logical --> FTN logical */
#if __EXTRA_UNDERLINE
#   define FTN(x)       x/**/_          
#   define FTCALL(x)    x/**/_      
#else
#   if  MICROSOFT
#       define FTN(x)   fortran x
#   else
#       define FTN(x)   x               /* to be called from Fortran */
#   endif
#   define FTCALL(x)    x               /* to call a Fortran function */
#endif

then each function is defined, e.g, FTN(name)(arg) float*arg{...etc...}.
If a C routine needs to call "name", it will instead use FTCALL(name)(&x).
The C-compiler script we use on each platform defines an identifiying
constant (of our devising - we choose not to rely on what compilers have
as builtin) as 1 - eg, VMSVAX on you-guess-what, DECMIPS on DECstations,
and so on.  It so happens that currently all of our machines whose Fortran
compilers want a trailing underline accept the old cpp trick of empty
comment for token-pasting; on ANSI C compilers, we'd use the ## pp operator.

There are of course many other macros to facilitate C<->Fortran interface
in a portable way, I just excerpted the portion having to do with trailing
underlines on names.
-- 
Alex Martelli - CAD.LAB s.p.a., v. Stalingrado 53, Bologna, Italia
Email: (work:) martelli at cadlab.sublink.org, (home:) alex at am.sublink.org
Phone: (work:) ++39 (51) 371099, (home:) ++39 (51) 250434; 
Fax: ++39 (51) 366964 (work only), Fidonet: 332/407.314 (home only).



More information about the Comp.unix.questions mailing list