Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if C code (which needs 'extern C') is compiled in C++

Tags:

c++

c

extern

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?

like image 901
fferri Avatar asked Mar 11 '19 10:03

fferri


People also ask

Is extern C needed?

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.

Can you use extern C in C?

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.

Does C need to be compiled?

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.

When should I use extern C?

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.


1 Answers

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.

like image 167
StoryTeller - Unslander Monica Avatar answered Sep 21 '22 23:09

StoryTeller - Unslander Monica