简体   繁体   English

如何在C中使用具有相同名称的不同枚举

[英]How to use different enums that have the same names in C

I have in one library, liba , an enum like this: 我在一个库liba中有一个这样的枚举

typedef enum LIB_A_ENUM {
  FOO,
  BAR
} LIB_A_ENUM

In libb I have another enum: libb我还有另一个枚举:

typedef enum LIB_B_ENUM {
  FOO,
  BAR,
  BAZ // has a few different ones.
} LIB_B_ENUM

I would like to use both of them in libb like this: libb这样在libb使用它们:

int
some_function() {
  if (LIB_A_ENUM.FOO) {
    // ...
  } else if (LIB_B_ENUM.FOO) {
    // ...
  }
}

Wondering how to do that sort of thing. 想知道如何做这种事情。 I'm imagining I should just create a bunch of global variables like: 我在想应该只创建一些全局变量,例如:

LIB_A_ENUM LIB_A_ENUM_FOO = FOO;
LIB_A_ENUM LIB_A_ENUM_BAR = BAR;
// ...
LIB_B_ENUM LIB_B_ENUM_FOO = FOO;
LIB_B_ENUM LIB_B_ENUM_BAR = BAR;
LIB_B_ENUM LIB_B_ENUM_BAZ = BAZ;
// ...

int
some_function() {
  if (LIB_A_ENUM_FOO) {
    // ...
  } else if (LIB_B_ENUM_FOO) {
    // ...
  }    
}

Wondering if that is the sort of approach to do it, or if there is a better way. 想知道这是否是执行此操作的方法,或者是否有更好的方法。

Actually, I realize you can't even have two different enums with the same keys. 实际上,我知道您甚至不能拥有具有相同键的两个不同的枚举。 So perhaps the best thing is to just have the enum values be globally unique. 因此,最好的办法就是让枚举值在全局范围内唯一。 I'm not sure. 我不确定。

You're right. 你是对的。 Since the enum values are store in global scope, they have to be globally unique. 由于枚举值存储在全局范围内,因此它们必须是全局唯一的。 The usual methods to prevent name collision in enum is to add the name enum's name as prefix for each of the enum values. 防止枚举中名称冲突的常用方法是为每个枚举值添加名称枚举名称作为前缀。 It's kinda verbose but it should prevent errors in most cases. 这有点冗长,但在大多数情况下应该可以防止错误。

typedef enum LIB_A_ENUM {
  LIB_A_ENUM_FOO,
  LIB_A_ENUM_BAR
} LIB_A_ENUM;

typedef enum LIB_B_ENUM {
  LIB_B_ENUM_FOO,
  LIB_B_ENUM_BAR,
  LIB_B_ENUM_BAZ
} LIB_B_ENUM;

You can't. 你不能 The C language requires that the names of enumeration constants do not clash with each other and other identifiers in the same scope . C语言要求枚举常量的名称与相同范围内的其他标识符不相互冲突。 Not even global variables are going to help because you cannot #include the 2 headers at the same time... 甚至全局变量也无济于事,因为您无法同时#include 2个标头...

So your choices boil down to: 因此,您的选择可以归结为:

  • change the enumeration constants so that they will have a prefix... (preferred!) 更改枚举常量,使其具有前缀...(首选!)

    • if you can't change the library headers, then perhaps you can #define a macro before inclusion of the clashing header, and #undef afterwards 如果您无法更改库标头,则可以在包含冲突标头之前#define宏,然后#undef
  • don't use them in the same translation unit 不要在同一个翻译单元中使用它们

  • or if you're really lucky, you can #include one of the headers within a function ; 或者,如果您真的很幸运,可以在函数中包含 #include之一; the definition there wouldn't clash with the outer one. 定义不会与外部定义冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM