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:

    Many people will say to working mothers, in effect, “I don’t think you can have it all.” The phrase for “have it all” is code for “have your cake and eat it too.” What these people really mean is that achievement in the workplace has always come at a price—usually a significant personal price; conversely, women who stayed home with their children were seen as having sacrificed a great deal of their own ambition for their families.
    Anne C. Weisberg (20th century)