Summary - ABI
- C++ course
- Expert
- Lesson 24/47
- 5 min
Combine mangling, extern C and stability to write a C-compatible library.
Summary - ABI
In this group you saw the core ABI concepts: ABI definition, name mangling, Itanium ABI, extern C and ABI stability. All ensure that compiled code stays compatible.
Now you will combine them in an extern C function example. You will declare and call an unmangled function with extern "C"; this is the basic pattern for bridging C and C++.
extern C function
To define an extern "C" function, prefix with extern "C": extern "C" int compute(int x) { return x + 100; }. The symbol name is compute; no mangling is performed.
In main, std::cout << compute(23); gives 123. This is the basic pattern for calling a C library from a C++ program; it also makes a C++ function accessible from C code.
Practice Write the extern C compute function
Write extern "C" int compute(int x) with body return x + 100;. In main write std::cout << compute(23);.
Starter code
#include <iostream>
// Define the compute function with extern "C" here
int main() {
// Call compute and print it
return 0;
}Sample solution
#include <iostream>
extern "C" int compute(int x) {
return x + 100;
}
int main() {
std::cout << compute(23);
return 0;
}Expected output
123
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();- Shrinks class size
- Hides the code
- Speeds up the program
- Turns off name mangling Correct answer
Explanation: extern C keeps the symbol name identical to the source code.
2 Complete the extern C declaration
extern "____" void greet();
extern "C" void greet();
Explanation: extern "C" requests C linkage.
3 Match each concept to its trait
| Term | Meaning |
|---|---|
ABI |
Binary compatibility |
name mangling |
Symbol naming |
extern C |
Unmangled symbol |
PIMPL |
Hidden implementation |