| C++ Migration Guide |
Moving From C to C++
This chapter describes how to move programs from C to C++.
C programs generally require little modification to compile as C++ programs. C and C++ are link compatible; you don't have to modify compiled C code to link it with C++ code. See The C++ Programming Language, by Margaret A. Ellis and Bjarne Stroustrup, for more specific information on the C++ language.
6.1 Reserved and Predefined Words
TABLE 6-1 shows all reserved keywords in C++ and C, plus keywords that are predefined by C++. Keywords that are reserved in C++ but not in C are shown in
boldface.
__STDC__is predefined to the value 0. For example:
#include <stdio.h>main(){#ifdef __STDC__printf("yes\n");#elseprintf("no\n");#endif#if __STDC__ ==0printf("yes\n");#elseprintf("no\n");#endif}The following table lists reserved words for alternate representations of certain operators and punctuators specified in the current ANSI/ISO working paper from the ISO C++ Standards Committee.
TABLE 6-2 C++ Reserved Words for Operators and Punctuators andbitornotorxorand_eqcomplnot_eqor_eqxor_eqbitand
6.2 Creating Generic Header Files
K&R C, ANSI C, and C++ require different header files. To make C++ header files conform to K&R C and ANSI C standards so that they are generic, use the macro _ _
cplusplusto separate C++ code from C code. The macro _ _STDC_ _ is defined in both ANSI C and C++. Use this macro to separate C++ or ANSI C code from K&R C code. For more information, see the C++ Programming Guide.
Note Early C++ compilers pre-defined the macroc_plusplus, which is no longer supported. Use__cplusplusinstead.
6.3 Linking to C Functions
The compiler encodes C++ function names to allow overloading. To call a C function, or a C++ function "masquerading" as a C function, you must prevent this encoding. Do so by using the
extern"C"declaration. For example:
extern "C" {double sqrt(double); //sqrt(double) has C linkage}This linkage specification does not affect the semantics of the program using
sqrt(),but simply causes the compiler to use the C naming conventions forsqrt().Only one of a set of overloaded C++ functions can have C linkage. You can use C linkage for C++ functions that you intend to call from a C program, but you would only be able to use one instance of that function.
You cannot specify C linkage inside a function definition. Such declarations can only be done at the global scope.
|
Sun Microsystems, Inc. Copyright information. All rights reserved. Feedback |
Library | Contents | Previous | Next | Index |