使用“ extern C”。与非函数调用相关的声明 [英] Using "extern C" on non function call related declarations

查看:144
本文介绍了使用“ extern C”。与非函数调用相关的声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道之前曾问过关于外部 C 的问题,但是我收到的信号不一,希望有人指出我的最佳做法是什么下面的情况。我已经为Linux编写了驱动程序,并定义了几个 struct 以及一些 _IO _IOR _IOW 定义,用于 ioctl(...)调用。我的结构都不包含任何函数,下面是 struct enum ioctl 我使用的是:

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

我的问题是,是否需要在此标头中添加外部 C ?标头在我的驱动程序中定义,该驱动程序用C编写,并由用C ++编写的用户程序使用。我认为是因为没有成员函数或特定的库函数调用,因此不需要 extern C
另外,将我的枚举更改为以下内容是否安全,而没有外部 C

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



编辑:



我的标题已经包裹在外部 C 中。我试图了解不调用函数的项目是否需要这样做,并且名称重整是一个问题。

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.

推荐答案

标准C ++, extern C 仅影响:函数类型,函数名称和变量名称。不使用枚举定义。

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.

有条件的枚举类是个坏主意。您可能最终会导致 enum 在C中的大小不同于C ++中的大小,从而导致互操作性问题。这两个标准都没有涉及,但是为了实现互操作性,最好确保两种语言使用完全相同的代码,而不是外部 C

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

这篇关于使用“ extern C”。与非函数调用相关的声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆