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 mangle symbols in the way that C++ compilers do.
- Depending on the compiler and architecture, it also may be the case that calling conventions differ between the two languages.
For these reasons, for C++ code to call a C function foo
, the C++ code must prototype foo
with extern "C"
. Likewise, for C code to call a C++ function bar
, the C++ code for bar
must be declared with extern "C++"
.
A common practice for header files to maintain both C and C++ compatibility is to make its declaration be extern "C"
for the scope of the header:
Differences between C and C++ linkage and calling conventions can also have subtle implications for code that uses function pointers. Some compilers will produce non-working code if a function pointer declared extern "C"
points to a C++ function that is not declared extern "C"
.
For example, the following code:
void my_function; extern "C" void foo(void (*fn_ptr)(void)); void bar { foo(my_function); }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 my_function
is not declared with C linkage and calling conventions, but is being passed to the C function foo
.
Read more about this topic: Compatibility Of C And C++
Famous quotes containing the word code:
“...I had grown up in a world that was dominated by immature age. Not by vigorous immaturity, but by immaturity that was old and tired and prudent, that loved ritual and rubric, and was utterly wanting in curiosity about the new and the strange. Its era has passed away, and the world it made has crumbled around us. Its finest creation, a code of manners, has been ridiculed and discarded.”
—Ellen Glasgow (18731945)