C ++保留符号作为C变量名

我在C ++项目中使用外部C库。

标头包含一个带有名为class的变量的结构:

 #ifdef __cplusplus extern "C" { #endif struct something_t { ... sometype class; }; #ifdef __cplusplus } #endif 

g ++不喜欢这个并抱怨“错误:’之前的预期标识符’;’ 令牌”。

我有什么选择?

  1. 我可以重命名class ,但这很麻烦,打破了上游兼容性。
  2. 我可以要求上游项目重命名变量,但这可能很难。
  3. 我可以使用预处理器在头文件中重新定义class#define class class_有任何副作用吗?
  4. 还有其他建议吗?

处理这种情况的最佳方法是什么?

结果:根据选项2的主要偏好,我最终选择在上游库中启动重命名。

正如其他人已经在评论中提到的那样,最好的选择是围绕那些东西编写另一个C API层,它只在内部使用另一个API。

与此违规struct定义相关的任何内容都应仅通过不透明指针导出。

在C ++中,您可以使用已清理的C-API。


这是一个小草图:

ThirdParty.h (包含用c ++编译的违规代码)

 #ifdef __cplusplus extern "C" { #endif struct something_t { ... sometype class; }; struct something_t* CreateSomething(); // Does memory allocation and initialization void DoSomething(struct something_t* something); #ifdef __cplusplus } #endif 

MyApiWrapper.h

 #ifdef __cplusplus extern "C" { #endif typedef void* psomething_t; struct psomething_t MyCreateSomething(); // Does memory allocation and initialization void MyDoSomething(psomething_t something); #ifdef __cplusplus } #endif 

MyApiWrapper.c

 #include "ThirdParty.h" struct psomething_t MyCreateSomething() { psomething_t psomething = (psomething_t)CreateSomething(); return psomething; } void MyDoSomething(psomething_t something) { DoSomething((struct something_t*)psomething); } 

关于您考虑的解​​决方案

  1. 我可以要求上游项目重命名变量,但这可能很难

你当然应该报告这个bug让他们知道。 如果是git-hub托管项目,请准备拉取请求。

无论如何,他们准备好他们可能没有及时回应,你应该总是有上面提到的“计划B” 。 它会工作,不管……

  1. 我可以使用预处理器在头文件中重新定义类:#define class class_有任何副作用吗?

它可能是一种可行的方式,如果这个特定符号( class )出现的任何地方是普通的c代码,并且第三方c代码的其他部分(例如作为库)不依赖于该符号(这是不可能的)。