skip to content

In C++, why does a C caller get an undefined symbol for a function compiled as C++, and what does extern "C" change?

level: middleimportance: must knowfreq 62%

answer

  1. the symbol is not the source name
  2. parameter types in the symbol
  3. language linkage
  4. one C name, no overloads
  5. the __cplusplus guard

basics

~20 s

C++ compilers mangle names, encoding namespace, class and parameter types into the symbol, so a C caller looking for the plain name finds nothing. extern "C" gives the function C language linkage: an unmangled name, and therefore no overloading.

solid answer

~40 s

A C++ compiler turns `sdk::scale(int)` into a **mangled** symbol so overloads and namespaces get distinct linker names; under the Itanium C++ ABI used by GCC and Clang on Linux and macOS it becomes `_ZN3sdk5scaleEi`, while MSVC uses its own decoration. A C compiler emits plain names, so a C file calling `plugin_init` looks for `plugin_init` and the C++ definition named `_Z11plugin_initi` never matches. Declaring the function `extern "C"` gives it C language linkage: the compiler uses the platform's C naming, so C and C++ agree. The price is that two `extern "C"` functions cannot share a name, even in different namespaces, so there is no overloading. Headers shared with C wrap declarations in `#ifdef __cplusplus` / `extern "C" {`. Tools such as `c++filt` turn mangled names back into readable signatures.

code

cpp · 7 lines
cpp
namespace sdk {
  int scale(int v) { return v * 2; }
  double scale(double v) { return v * 2.0; }
  struct Plugin { int id; int run(int x) const { return x + id; } };
  int call(const Plugin& p, int x) { return p.run(x); }
}
extern "C" int sdk_abi_version() { return 3; }

go deeper

for a junior

Recall that C++ symbol names encode parameter types, so C cannot find them, and that extern "C" with the __cplusplus guard fixes the shared header.

for a middle

Explain what an Itanium mangled name encodes, why extern "C" rules out overloading, and how to read nm and c++filt output when a link fails.

for a senior

Use mangling to reason about ABI: what changes a symbol loudly, what changes behaviour silently, and why the MSVC and Itanium conventions do not mix.

for a principal

Decide where a product needs a C-linkage boundary, accepting the loss of overloading, exceptions across the boundary and C++ types in exchange for toolchain independence.

## Why C++ needs mangling A linker matches **symbols** by exact string. C has one function per name, so a C compiler can use the source name (on macOS with a leading underscore, which every Mach-O C symbol gets). C++ allows several functions with one name – overloads, the same name in different namespaces and classes, `const` and non-`const` member functions – and each needs a distinct linker symbol. The compiler therefore **mangles** each name into a string that encodes: - the enclosing namespaces and classes, - the function name, - the parameter types, - qualifiers such as `const` on a member function, and template arguments. For a non-template function the return type is **not** encoded. That detail matters later, because a changed return type does not change the symbol. ## Mangling belongs to the ABI, not the standard The C++ standard never specifies mangling. It defines **language linkage** and leaves the representation to the implementation; its own note says a language linkage may be associated with a particular way of representing names and a calling convention. In practice: | Platform convention | Who uses it | `sdk::scale(int)` becomes | |---|---|---| | Itanium C++ ABI | GCC and Clang on Linux, macOS and most non-Windows targets | `_ZN3sdk5scaleEi` | | MSVC decorated names | MSVC, and Clang when targeting the MSVC ABI | `?scale@sdk@@YAHH@Z` | Reading the Itanium form: `_Z` starts a mangled name, `N...E` wraps a nested name, `3sdk` and `5scale` are length-prefixed identifiers, and the trailing `i` is the `int` parameter. A namespace-scope variable `sdk::scale` would be `_ZN3sdk5scaleE`, with no parameter list. `c++filt` (or `llvm-cxxfilt`) demangles: piping `nm` output through it shows `sdk::scale(int)`. Member function qualifiers show up too: `_ZNK3sdk6Plugin3runEi` is `sdk::Plugin::run(int) const`, the `K` marking the `const`, and `_ZN3sdk4callERKNS_6PluginEi` shows a `const sdk::Plugin&` parameter as `RK` plus a back-reference. Because the two conventions differ, objects compiled for the MSVC ABI and for the Itanium ABI cannot link to each other's C++ symbols; only C-linkage functions line up. ## What `extern "C"` does `extern "C"` is a **linkage specification**. Inside it, functions and variables with external linkage, and function types, get **C language linkage**: 1. The symbol uses the platform's C naming: `extern "C" int plugin_init(int)` is `plugin_init` (shown by `nm` on macOS as `_plugin_init`). 2. Matching a symbol with no parameter types, the standard treats two C-linkage declarations with the same name as the **same entity**, even in different namespaces. Declaring `plugin_scale(int)` and `plugin_scale(double)` both `extern "C"` is an error; Clang reports "conflicting types for 'plugin_scale'". 3. The body is still C++: it may call C++ functions, use classes and templates internally, and throw. Only the boundary is C-shaped. 4. C language linkage is ignored for class member functions, so a member function cannot be made callable from C this way. ## The shared-header idiom A header used by both languages guards the specification, because a C compiler does not know `extern "C"`: ```cpp #ifdef __cplusplus extern "C" { #endif int plugin_init(int flags); int sdk_abi_version(void); #ifdef __cplusplus } #endif ``` The C++ implementation includes the same header, so its definitions pick up C linkage from the earlier declarations, and a C host links against them directly. ## Diagnosing the original failure The symptom is a link error naming the plain symbol: on macOS, `Undefined symbols for architecture arm64: "_plugin_init", referenced from: _main in host.o`. The checklist: - Run `nm` on the C++ object and look for the mangled form `_Z11plugin_initi` – if it is there, the declaration the C++ file saw lacked `extern "C"`. - Check that the C++ source includes the shared header before defining the function, so the linkage is inherited. - Remember that only the declaration seen by the definition decides the symbol; adding `extern "C"` on the C side is impossible and unnecessary. ## Why interviewers ask it It is the doorway question to ABI work, and it comes up whenever C++ code is called from C, from another language's foreign-function interface or from a plugin host: it shows whether a candidate knows that source names and linker symbols differ, that mangling is a platform convention rather than a language rule, and that a C boundary trades C++ features for a symbol every toolchain agrees on.

  • Can an extern "C" function take or return C++ types such as std::string?
    The compiler accepts it, because linkage controls the symbol name and calling convention, not the parameter types. But a C caller cannot construct or read a `std::string`, and two C++ sides built with different standard libraries disagree on its layout, so a C-callable boundary should use C types: pointers, sized integers, plain structs and opaque handles.
  • If you change a function's return type from int to long long, do callers still link?
    Yes, and that is the danger. For non-template functions the Itanium mangling encodes parameters but not the return type, so `sdk::level(int)` keeps the symbol `_ZN3sdk5levelEi`. Old callers link and then read the result as an `int`, a silent ABI break rather than a link error.
  • Does putting extern "C" functions in different namespaces let them share a name?
    No. The standard says two declarations with the same name that both have C language linkage declare the same entity, whatever namespace they are in, because the symbol has no room for a namespace. Two definitions are a redefinition; two incompatible declarations are an error.

Mangling is a parcel label that adds the street, flat number and recipient's details to the name; extern "C" writes only the name, so two parcels for the same name can no longer be told apart.

  • The C++ standard defines how names are mangled.
  • extern "C" means the function body must be written in C.
  • Two extern "C" functions can be overloaded on parameter types.
  • The return type is part of every mangled function name.
  • GCC, Clang and MSVC objects can call each other's C++ functions.
  • Putting extern "C" functions in different namespaces keeps them apart.