Search code examples
c++cenumsexternioctl

Using "extern C" on non function call related declarations


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
};

Edit:

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.


Solution

  • 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".