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:
“Hollywood keeps before its child audiences a string of glorified young heroes, everyone of whom is an unhesitating and violent Anarchist. His one answer to everything that annoys him or disparages his country or his parents or his young lady or his personal code of manly conduct is to give the offender a sock in the jaw.... My observation leads me to believe that it is not the virtuous people who are good at socking jaws.”
—George Bernard Shaw (18561950)