How do you call C code from C++ and C++ from C (extern "C")?
Short answer: C++ compilers mangle function names to encode namespaces and parameter types (for overloading), while C uses plain names. Declaring functions extern "C" tells the C++ compiler to use C linkage (unmangled names and the C calling convention), so C and C++ object files can link together. C headers used from C++ wrap their declarations in extern "C" guarded by #ifdef __cplusplus; C++ functions that C code must call (including interrupt handlers referenced by a C vector table) are defined extern "C".
/* hal_uart.h — usable from both C and C++ */
#ifndef HAL_UART_H
#define HAL_UART_H
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
void hal_uart_init(uint32_t baud);
void hal_uart_putc(char c);
#ifdef __cplusplus
}
#endif
#endif
/* irq.cpp — C++ handler with the exact name the startup file expects */
extern "C" void USART2_IRQHandler(void)
{
uart_driver.on_interrupt(); // forward into a C++ object
}
What can cross the boundary: plain functions with C-compatible parameter types (integers, pointers, POD structs, function pointers). Not classes with virtual functions, references, overloaded functions, templates or exceptions (an exception must never propagate into C code).
Common bugs
- An ISR written in C++ without
extern "C"gets a mangled name (_Z17USART2_IRQHandlerv), so the weak default handler in the vector table is used instead and the interrupt "never fires" or hangs inDefault_Handler. - Passing a C++ member function as a C callback: use a static member or a free function with a
void *contextparameter that you cast back to the object. - Mismatched struct layouts if C++ adds a vptr or non-standard-layout members; check with
static_assert(std::is_standard_layout_v<T>).