In earlier discussions (such as Chapter 6), you have seen how the extern keyword specifies that a variable or function has external linkage. This means that the variable or function referenced is defined in some other source file or later on in the same file.
In C and C++, the extern keyword can be used with a string. The string indicates that another language’s linkage conventions are being used for the identifier(s) being defined. For C++ programs, the default string is “C++.”
In C++, functions are overloaded by default. This causes the C++ compiler to assign a new name to each function. You can prevent the compiler from assigning a new name to each function by preceding the function definition with extern “C”. This is necessary so that C functions and data can be accessed by C++ code. Naturally, this is only done for one of a set of functions with the same name. Without this override, the linker would find more than one global function with the same name. Currently, “C” is the only other language specifier supported by Visual C++. The syntax for using extern “C” takes this form:
The following listing demonstrates how extern “C” is used with a single-function prototype:
extern “C” int fprintf(FILE *stream, char *format, ...);
To modify a group of function prototypes, a set of braces, { }, is needed:
extern “C” { . . . }
The next code segment modifies the getc( ) and putc( ) function prototypes:
extern “C” { int getc(FILE *stream); int putc(int c, FILE *stream); }
The following example program demonstrates how to use extern “C”:
// // clink.cpp // C++ program demonstrating how to link C++ code // to C library functions // Copyright (c) Chris H. Pappas and William H. Murray, 1998 //
All the Visual C++ include files use extern “C”. This makes it possible for a C++ program to use the C run-time library functions. Rather than repeat extern “C” for every definition in these header files, the following conditional statement pair surrounds all C header file definitions:
// 3-statements found at the beginning of header file.
#ifdef __cplusplus extern “C” { #endif
// 3-statements found at the end of the header file.
#ifdef __cplusplus } #endif
When compiling a C++ program, the compiler automatically defines the __cplusplus name. This in turn makes the extern “C”{ statement and the closing brace, }, visible only when needed.