Thursday, January 17, 2008

Alternate linkage specifications

What happens if you’re writing a program in C++ and you want to

use a C library? If you make the C function declaration,

float f(int a, char b);

the C++ compiler will decorate this name to something like

_f_int_char to support function overloading (and type-safe

linkage). However, the C compiler that compiled your C library has

most definitely not decorated the name, so its internal name will be

_f. Thus, the linker will not be able to resolve your C++ calls to f( ).

The escape mechanism provided in C++ is the alternate linkage

specification, which was produced in the language by overloading

the extern keyword. The extern is followed by a string that

specifies the linkage you want for the declaration, followed by the

declaration:

extern "C" float f(int a, char b);

This tells the compiler to give C linkage to f( ) so that the compiler

doesn’t decorate the name. The only two types of linkage

specifications supported by the standard are “C” and “C++,” but

compiler vendors have the option of supporting other languages in

the same way.

If you have a group of declarations with alternate linkage, put them

inside braces, like this:

extern "C" {

float f(int a, char b);

double d(int a, char b);

}

Or, for a header file,

extern "C" {

#include "Myheader.h"

}

Most C++ compiler vendors handle the alternate linkage

specifications inside their header files that work with both C and

C++, so you don’t have to worry about it.

No comments: