extern C
- C++ course
- Expert
- Lesson 22/47
- 5 min
Learn C compatibility with extern C.
extern C
The extern "C" linkage specification requests C linkage for a function or variable; that is, name mangling is turned off. The symbol stays exactly as in the source code.
Example: extern "C" void greet() produces the symbol greet (no mangling). This lets a C-compiled library be called from a C++ program. Conversely, C code can call a C++ function declared with extern "C". It is the bridge between C and C++.
Mixing C and C++
If a header file is used from both C and C++, the extern "C" block is guarded with #ifdef __cplusplus. The C compiler does not see this block; the C++ compiler does.
Example: #ifdef __cplusplus\nextern "C" {\n#endif\nvoid greet();\n#ifdef __cplusplus\n}\n#endif. This idiom is common in standard C libraries and embedded systems. The C++ side calls the unmangled greet symbol; the C side does not mangle anyway.
Practice Write hello with extern C
Write extern "C" void hello() with body std::cout << "Hello";. In main write hello();.
Starter code
#include <iostream>
// Define the hello function with extern "C" here
int main() {
// Call hello
return 0;
}Sample solution
#include <iostream>
extern "C" void hello() {
std::cout << "Hello";
}
int main() {
hello();
return 0;
}Expected output
Hello
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does extern "C" do?
extern "C" void greet();- Translates code to C
- Turns off name mangling Correct answer
- Speeds up the program
- Removes classes
Explanation: extern C keeps the symbol name identical to the source code.
2 Complete the extern C block
extern "____" { void legacy(); }
extern "C" { void legacy(); }
Explanation: extern "C" requests C linkage.
3 Match each piece to its role
| Term | Meaning |
|---|---|
extern "C" |
C linkage |
void greet() |
Unmangled symbol |
_Z3foov |
Mangled symbol |
namespace |
Namespace |