The extern "C" mechanism provides the ability to interact with C code. This allows the use of C libraries and facilitates the connection between C++ and other languages.
Background: Since the inception of C++, it was built on the foundation of C but had its own features, including 'name mangling', to support function overloading and other capabilities.
Problem: Function names in C++ are compiled into symbols with additional structure (mangled), but C does not have such transformation. As a result, it is impossible to simply include a C header file in a C++ compiler without additional effort.
Solution:
Wrapping functions in extern "C" prevents name mangling, making them visible to code compiled by a C compiler.
Example code:
#ifdef __cplusplus extern "C" { #endif void foo(int); #ifdef __cplusplus } #endif
Key features:
Can functions with extern "C" be overloaded?
No, overloading is not possible since it uses the standard C function name.
What will happen if a template function is declared as extern "C"?
A compilation error, as templates are a separate feature of C++ and are not supported in C.
Can extern "C" be used at the class level?
No, it is only for functions and variables, not for classes or methods.
A C++ project connects a third-party C library without extern "C", and then the code does not link due to symbol name mismatch.
Pros:
Cons:
extern "C" is used in header files when integrating third-party C libraries.
Pros:
Cons: