CodeBlanks Logo Icon CodeBlanks

Summary - ABI

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

main.cpp
#include <iostream>

// Define the compute function with extern "C" here

int main() {
    // Call compute and print it
    return 0;
}

Sample solution

main.cpp
#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?

main.cpp
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

Question
extern "____" void greet();
Answer
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

All lessons in Expert