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 extern keyword is used to extend the visibility of variables/functions. Since functions are visible throughout the program by default, the use of extern is not needed in function declarations or definitions. Its use is implicit.
By declaring a function with extern "C" , it changes the linkage requirements so that the C++ compiler does not add the extra mangling information to the symbol. This pattern relies on the presence of the __cplusplus definition when using the C++ compiler. If you are using the C compiler, extern "C" is not used.
C is a mid-level language and it needs a compiler to convert it into an executable code so that the program can be run on our machine.
The extern must be applied to all declarations in all files. (Global const variables have internal linkage by default.) extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention. The extern "C" modifier may also be applied to multiple function declarations in a block.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With