Compatibility of C and C++
4573232
220344718
2008-06-19T12:03:13Z
157.181.161.14
interwiki
{{ProgLangCompare}}
The [[C programming language|C]] and [[C++]] [[programming languages]] are closely related. C++ grew out of C and is mostly a superset of the latter. Due to this, C code is often developed with C++ [[Integrated development environment|IDEs]], integrated with C++ code, and compiled in C++ [[compiler]]s. While most C source code will compile as C++ code without any changes, certain language differences prevent C++ from being a strict superset of C.
C++ introduces many features that are not available in C — C++ code is not valid C code. Here, however, we focus on differences that cause valid C code to be invalid C++ code, or to be valid in both languages but to behave differently in C and C++.
[[Bjarne Stroustrup]], the creator of C++, has suggested [http://www.research.att.com/~bs/sibling_rivalry.pdf] that the incompatibilities between C and C++ should be reduced as much as possible in order to maximize inter-operability between the two languages. Others have argued that since C and C++ are two different languages, compatibility between them is useful but not vital; according to this camp, efforts to reduce incompatibility should not hinder attempts to improve each language in isolation. The official rationale for the 1999 C standard (C99) [http://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf] "endorse<nowiki>[d]</nowiki> the principle of maintaining the largest common subset" between C and C++ "while maintaining a distinction between them and allowing them to evolve separately," and was "content to let C++ be the big and ambitious language."
Several additions of C99 are not supported in C++ or conflict with C++ features, such as variadic macros, compound literals, variable-length arrays, and native complex-number types. The <code>long long int</code> datatype and <code>restrict</code> qualifier defined in C99 are not included in any official C++ standard, but some compilers such as [[GNU Compiler Collection]]<ref>[http://gcc.gnu.org/onlinedocs/gcc/Restricted-Pointers.html#Restricted-Pointers Restricted Pointers] from ''Using the GNU Compiler Collection (GCC)''</ref> provide them as an extension. On the other hand, C99 has reduced some other incompatibilities by incorporating C++ features such as <code>//</code> comments and mixed declarations and code.
==Constructs valid in C but not C++==
One commonly encountered difference is that C allows a <code>void*</code> pointer to be assigned to any pointer type without a cast, whereas C++ does not; this idiom appears often in C code using <code>malloc</code> memory allocation. For example, the following is valid in C but not C++:
<source lang="c">
void* ptr;
int *i = ptr; /* Implicit conversion from void* to int* */
</source>
or similarly:
<source lang="c">int *j = malloc(sizeof(int) * 5); /* Implicit conversion from void* to int* */</source>
In order to make the code compile in both C and C++, one must use an explicit cast:
<source lang="c">
void* ptr;
int *i = (int *) ptr;
int *j = (int *) malloc(sizeof(int) * 5);
</source>
Another portability issue from C to C++ are the numerous additional keywords that C++ introduced. This makes C code that uses them as identifiers invalid in C++. For example:
<source lang="c">
struct template
{
int new;
struct template* class;
};
</source>
is legal C code, but is rejected by a C++ compiler, since the keywords "template", "new" and "class" are reserved.
C++ compilers prohibit goto from crossing an initialization, as in the following C99 code:
<source lang="c">
void fn(void)
{
goto flack;
int i = 1;
flack:
;
}
</source>
There are many other C syntaxes which are invalid or behave differently in C++ [http://david.tribble.com/text/cdiffs.htm]:
* The comma operator can result in an "l-value" (a quantity that can be used for the left-hand side of an assignment) in C++, but not in C.
* C does not allow a given <code>typedef</code> to be duplicated in the same scope, whereas C++ allows redundant <code>typedef</code>s.
* Enumeration constants (<code>enum</code> values) are always of type <code>int</code> in C, whereas they are distinct types in C++ and may have size different from that of <code>int</code>.
* C++ identifiers are not allowed to contain two or more consecutive underscores in any position. C identifiers are not allowed to start with two or more consecutive underscores, but may contain them in other positions.
* C++ also changes some C standard-library functions to add additional <code>const</code> qualifiers, e.g. <code>strchr</code> returns <code>char*</code> in C and <code>const char*</code> in C++.
* In both C and C++ one can define nested <code>struct</code> types, but the scope is interpreted differently (in C++, a nested <code>struct</code> is defined only within the scope/namespace of the outer <code>struct</code>).
* Non-prototype ("K&R"-style) function declarations are not allowed in C++, although they have also been deprecated in C since 1990. Similarly, implicit function declarations (using functions that have not been declared) are not allowed in C++, but have also been deprecated in C since 1999.
* C allows <code>struct</code>, <code>union</code>, and <code>enum</code> types to be declared in function prototypes, whereas C++ does not.
* A <code>struct</code>, <code>union</code>, or <code>enum</code> declaration in C++ is a first class type, while in C it is not.
==Constructs that behave differently in C and C++==
There are a few syntactical constructs that are valid in both C and C++, but produce different results in the two languages.
For example, character literals such as <code>'a'</code> are of type <code>int</code> in C and of type <code>char</code> in C++, which means that <code>sizeof('a')</code> gives different results in the two languages.
The <code>static</code> keyword is used in C to restrict a function or global variable to file scope (internal linkage). This is also valid in C++, although C++ deprecates this usage in favor of anonymous namespaces (which are not available in C). Also, C++ implicitly treats any <code>const</code> global as file scope unless it is explicitly declared <code>extern</code>, unlike C in which <code>extern</code> is the default. Conversely, <code>inline</code> functions in C are of file scope whereas they have external linkage by default in C++.
Several of the other differences from the previous section can also be exploited to create code that compiles in both languages but behaves differently. For example, the implicit typedefs created by C++ struct declarations can change the meaning of an identifier in a given scope.
Both C99 and C++ have a boolean type <code>bool</code> with constants <code>true</code> and <code>false</code>, but they behave differently. In C++, <code>bool</code> is a built-in type and a reserved keyword. In C99, a new keyword, _Bool, is introduced as the new boolean type. It behaves much like an unsigned int, but the values are always constrained to 0 and 1. The header <code>stdbool.h</code> provides a typedef for <code>bool</code> that maps to _Bool.
== Linking C and C++ code ==
While C and C++ maintain a large degree of source compatibility, the object files their respective compilers produce can have important differences that manifest themselves when intermixing C and C++ code. Notably:
* C compilers do not [[name mangling|name mangle]] symbols in the way that C++ compilers do.
* Depending on the compiler and architecture, it also may be the case that [[calling convention]]s differ between the two languages.
For these reasons, for C++ code to call a C function <code>foo()</code>, the C++ code must [[prototype]] <code>foo()</code> with <code>extern "C"</code>. Likewise, for C code to call a C++ function <code>bar()</code>, the C++ code for <code>bar()</code> must be declared with <code>extern "C"</code>.
A common practice for [[header file]]s to maintain both C and C++ compatibility is to make its declaration be <code>extern "C"</code> for the scope of the header:
<source lang="c">
/* Header file foo.h */
#ifdef __cplusplus /* If this is a C++ compiler, use C linkage */
extern "C" {
#endif
/* These functions get C linkage */
void foo();
struct bar { /* ... */ };
#ifdef __cplusplus /* If this is a C++ compiler, end C linkage */
}
#endif
</source>
Differences between C and C++ linkage and calling conventions can also have subtle implications for code that uses [[function pointer]]s. Some compilers will produce non-working code if a function pointer declared <code>extern "C"</code> points to a C++ function that is not declared <code>extern "C"</code>.[http://docs.sun.com/source/819-3689/Ch3.Std.html#pgfId-18503]
For example, the following code:
<source lang="c">
void my_function();
extern "C" void foo(void (*fn_ptr)(void));
void bar()
{
foo(my_function);
}
</source>
Using [[Sun Microsystems]]' C++ compiler, this produces the following warning:
$ CC -c test.cc
"test.cc", line 6: Warning (Anachronism): Formal argument fn_ptr of type
extern "C" void(*)() in call to foo(extern "C" void(*)()) is being passed
void(*)().
This is because <code>my_function()</code> is not declared with C linkage and calling conventions, but is being passed to the C function <code>foo()</code>.
==References==
{{Reflist}}
* [http://www.coding-guidelines.com/cbook/c90c++.pdf Detailed comparison] , sentence by sentence, from a C Standard perspective.
* [http://david.tribble.com/text/cdiffs.htm Incompatibilities Between ISO C and ISO C++], David R. Tribble (Aug 2001).
* [http://docs.sun.com/source/819-3689/Ch3.Std.html#pgfId-18154 Sun Microsystems C++ Migration Guide, section 3.11], documentation on linkage issues for the Sun C++ compiler.
==External links==
{{wikibooks|C++ Programming|Programming Languages/Comparisons/C}}
{{CProLang}}
[[Category:Programming language comparisons]]
[[Category:C programming language]]
[[Category:C++]]
[[hu:C részhalmaz (C++)]]