I have a C header as part of a C++ library.
This C header would only make sense compiled by a C compiler, or by a C++ compiler within an extern "C" { ... }
block, otherwise unresolved link errors would happen.
I thought to add a block such as:
#ifdef __cplusplus
#error "Compiling C bindings with C++ (forgot 'extern \"C\"'?)"
#endif
in the C header, but unfortunately the __cplusplus
macro is defined also within an extern "C" { ... }
block.
Is there another way to detect this condition correctly?
The common practice is not to demand client code wraps your header in extern "C"
, but to do so conditionally yourself. For instance:
#ifdef __cplusplus
extern "C" {
#endif
// Header content
#ifdef __cplusplus
}
#endif
That way client code is automatically correct without doing anything beyond including the header.