Linkage Specifications -- Linking to Non-C++ Programs

C++Linkage between C++ and non-C++ code fragments is called language linkage. All function types, function names, and variable names have a language linkage, which by default is C++.

You can link C++ object modules to object modules produced using other source languages such as C by using a linkage specification. The syntax is:

>>-extern--string_literal--+-declaration---------------+-------><
                           |    .-----------------.    |
                           |    V                 |    |
                           '-{----+-------------+-+--}-'
                                  '-declaration-'
 
 

The string_literal is used to specify the linkage associated with a particular function. String literals used in linkage specifications should be considered as case-sensitive. All platforms support the following values for string_literal

 "C++" 
Unless otherwise specified, objects and functions have this default linkage specification.

 "C" 
Indicates linkage to a C procedure

Calling shared libraries that were written before C++ needed to be taken into account requires the #include directive to be within an extern "C" {} declaration.

extern "C" {
#include "shared.h"
}

The following example shows a C printing function that is called from C++.

//  in C++ program
extern "C" int displayfoo(const char *);
int main() {
    return displayfoo("hello");
}
 
/*  in C program     */
#include <stdio.h>
extern int displayfoo(const char * str) {
    while (*str) {
       putchar(*str);
       putchar(' ');
       ++str;
    }
    putchar('\n');
} 

Related References

IBM Copyright 2003