Adjusting Calling Conventions

HomeOverviewHow Do I

The calling convention determines how a program makes a call and where the parameters are passed. In a single-language program, calling conventions are nearly always correct, because there is one default for all modules and because header files enforce consistency between the caller and the called routine. In a mixed-language program, different languages cannot share the same header files. It’s easy to link Fortran and C modules that use different calling conventions, and the error isn’t apparent until the bad call is made at run time, causing immediate program failure. Therefore, you should check calling conventions carefully for each mixed-language call.

The following table summarizes how C and Fortran calling conventions work.

C and Fortran Calling Conventions

Calling convention Parameter passing Stack cleared by
C/C++ Pushes parameters on the stack, in reverse order (right to left) Caller
Fortran (__stdcall) Pushes parameters on the stack, in reverse order (right to left) Called function

In C and C++ modules, you can specify the Fortran calling convention by using the __stdcall keyword in a function prototype or definition. The __stdcall convention is also used by window procedures and API functions. For example, the following C language prototype sets up a function call to a subroutine using the Fortran calling convention:

extern void __stdcall fortran_routine (int n);

Instead of changing the calling convention of the C code, you can adjust the Fortran source code by using the C attribute, enclosed in brackets ([ ]). For example, the following declaration assumes the subroutine is called with the C calling convention:

      SUBROUTINE CALLED_FROM_C [C] (A)
      INTEGER*4 A

It should be clear that calling conventions need only agree between individual calls and the called routines, and that the conventions must be the same: Both caller and called routine must use the C/C++ convention or both must use the __stdcall convention (the Fortran default).

Note   In programs written for the graphical user interface of Windows, PASCAL, WINAPI, and CALLBACK are all defined with __stdcall. But the C language default is still cdecl.

The following table summarizes how to specify calling conventions. You can always specify calling conventions explicitly rather than relying on the default, which is a good technique for mixed-language programming.

Specifying Calling Conventions

Language C calling convention Fortran calling convention
C/C++ cdecl (default) __stdcall
Fortran C attribute STDCALL attribute (default)