Skip to content
AgileLogics
4 min read

Interfacing with C

Prerequisites: The Pimpl idiom

C++ can call C code directly, and vice versa, via extern "C" — which tells the C++ compiler not to name-mangle those functions, so a C linker (or C++ code linking against a C library) can find them by their plain name.

extern "C" {
    #include "some_c_library.h"
}

extern "C" void myFunctionCallableFromC(int x) {
    std::cout << "Called from C with: " << x << std::endl;
}

C++ name mangling encodes a function's parameter types into its linked symbol name (enabling overloading, which C has no concept of) — extern "C" disables that encoding for the functions it wraps, which is exactly why it's needed at every C/C++ boundary.