Mixed-Language Programming with C++

HomeOverviewHow Do I

C++ uses the same calling convention and parameter-passing techniques as C, but naming conventions are different because of C++ decoration of external symbols. By causing C++ to drop name decoration, the extern "C" syntax makes it possible for a C++ module to share data and routines with other languages.

The following example declares prn as an external function using the C naming convention. This declaration appears in C++ source code.

extern "C"
{
    void prn();
}

To call functions written in Fortran (or MASM), declare the function as you would in C and use a "C" linkage specification. For example, to call the Fortran function FACT from C++, declare it as follows:

extern "C" { int __stdcall FACT( int n ); }

The extern "C" syntax can be used to adjust a call from C++ to other languages, or to change the naming convention of C++ routines called from other languages. However, extern "C" can be used only from within C++. If the C++ code does not use extern "C" and cannot be changed, you can call C++ routines only by determining the name decoration and generating it from the other language. You can always determine the decoration by using the DUMPBIN utility. Use this approach only as a last resort, because the decoration scheme is not guaranteed to remain the same between versions.

Use of extern "C" has some restrictions:

For more information on the extern "C" linkage specification, see Linkage Specifications in C++ Language Reference.