Compatibility of C and C++ - Linking C and C++ Code

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:

/* 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

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:

    Motion or change, and identity or rest, are the first and second secrets of nature: Motion and Rest. The whole code of her laws may be written on the thumbnail, or the signet of a ring.
    Ralph Waldo Emerson (1803–1882)