Back to Comprehensive Rust

C++ ↔ C

src/unsafe-deep-dive/ffi/language-differences/cpp-and-c.md

latest1.3 KB
Original Source
<!-- Copyright 2026 Google LLC SPDX-License-Identifier: CC-BY-4.0 -->

C++ ↔ C

ConcernCC++
OverloadingManual/ad-hocAutomatic
Exceptions-Stack unwinding
DestructorsManual cleanupAutomatic via destructors (RAII)
Non-POD types-Objects with constructors, vtables, virtual bases
Templates-Compile-time code generation
<details>

C++ includes a number of features that don't exist in C with an FFI impact:

Overloading: Overloads become impossible to express because of name mangling

Exceptions: Must catch exceptions at the FFI boundary and convert them to error codes, as escaping exceptions in extern "C" functions constitute undefined behavior

Destructors: C callers won't run destructors; must expose explicit *_destroy() functions

Non-POD types: Must use opaque pointers across the FFI boundary as pass by value does not make sense

Templates: Cannot expose directly; must instantiate explicitly and wrap each specialization

</details>