I know questions regarding extern "C"
have been asked before but I am getting mixed signals and would like it if someone could point me to what the best practice is in the scenario below. I have written a driver for Linux and have several struct
defined as well as some _IO
, _IOR
, and _IOW
definitions for ioctl(...)
calls. None of my structures contain any functions, below is an example struct
, enum
and ioctl
that I use:
#ifdef __cplusplus
extern "C" {
#endif
enum Alignment
{
Left = 0,
Right = 1,
Middle = 3
};
struct Data
{
int Size;
void* Address;
};
#define foo _IOR(DRV_ID, 1, struct Data*);
#ifdef __cplusplus
}
#endif
My question is, do I need to add an extern "C"
to this header? The header is defined in my driver which is written in C and used by user programs written in C++. I figure because there are no member functions or specific library function calls I do not need extern "C"
.
Also, is it safe to change my enum
to below without extern "C"
:
#ifdef __cplusplus >= 201103L
enum class Alignment
#else
enum Alignment
#endif
{
Left = 0,
Right = 1,
Middle = 3
};
My header is already wrapped in extern "C"
. I'm trying to understand if this is needed for items that do not call functions and name mangling is an issue.
in Standard C++ , extern "C"
only affects: function types, function names and variable names. Not to enum
definitions.
Your compiler might do something beyond what the standard says, you'd have to consult its documentation.
The conditional enum class
is a bad idea. You might end up with the enum
having a different size in C than in C++, leading to problems with interoperability. This isn't covered by either standard, but for interoperability it'd be best to make sure the exact same code is used for both languages, other than extern "C"
.
There is a conflict here:
your code goes like this:
#ifdef __cplusplus >= 201103L
enum class Alignment
#else
enum Alignment
but extern "c"
should be put in the exact macro:
#ifdef __cplusplus
extern "C"
#endif
enum Alignment
the outcome, if you append both macros:
extern "C" enum class Alignment
but this is illegal, since C language doesn't knows such as declaration.
therefore, I guess that if you want to use extern "C"
, to be able to use the header from c, not only c++, you should gave up of the enum class
and use old fashion enum
type. if you decide to use the header only from c++, the extern "C"
is not needed, and you can use enum class
.
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