计数预处理器宏 [英] Counting preprocessor macros

查看:28
本文介绍了计数预处理器宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个宏代码,它允许我使用一个构造将 C 枚举和枚举名称列表定义为字符串.它使我不必重复枚举器名称(并可能为大型列表引入错误).

I have this macro code, which allows me to define both a C enum and a list of the enumerated names as strings using one construct. It prevents me from having to duplicate enumerator names (and possibly introducing errors for large lists).

#define ENUM_DEFINITIONS(F) 
  F(0, Item1) 
  F(5, Item2) 
  F(15, Item3) 
  ...
  F(63, ItemN)

然后:

enum Items {
  #define ITEM_ENUM_DEFINE(id, name) name = id,
    ENUM_DEFINITIONS(ITEM_ENUM_DEFINE)
  #undef ITEM_ENUM_DEFINE

当展开时,应该产生:

enum Items {
  Item1 = 0,
  Item2 = 5,
  Item3 = 15,
  ...
  ItemN = 63,
}

在实现文件中,我有这段代码:

In the implementation file, I have this code:

const char* itemNames[TOTAL_ITEMS];
int iter = 0;

#define ITEM_STRING_DEFINE(id, name) itemNames[iter++] = #name;
  ENUM_DEFINITIONS(ITEM_STRING_DEFINE)
#undef ITEM_STRING_DEFINE

当展开时,会产生:

itemNames[iter++] = "Item1";
itemNames[iter++] = "Item2";
itemNames[iter++] = "Item3";
...
itemNames[iter++] = "ItemN";

我想知道我以这种方式创建了多少个枚举器项,并且能够将其传递给编译时数组.在上面的示例中,这将在编译时确定 TOTAL_ITEMS = N.是否可以以这种方式计算宏调用?

I'd like to know how many enumerator items I've created in this fashion and be able to pass it to compile-time arrays. In the example above, this would be determining that TOTAL_ITEMS = N at compile-time. Is it possible to count macro invocations in this way?

我看到有人提到非标准的 COUNTER 宏,类似于 FILELINE 宏,但我希望还有一种更标准的方法.

I've seen mention of a non-standard COUNTER macro, similar to the FILE and LINE macros, but I'm hoping there is a more standard way.

也有兴趣了解是否有更好的方法来实现这一点而无需使用宏.

Would also be interested in hearing if there is a better way to achieve this without having to use macros.

推荐答案

以下应该可以工作:

#define ITEM_STRING_DEFINE(id, name) #name, // note trailing comma
const char *itemNames[] = {
  ENUM_DEFINITIONS(ITEM_STRING_DEFINE)
};

#define TOTAL_ITEMS (sizeof itemNames / sizeof itemNames[0])

编辑:感谢 Raymond Chen 指出我们不必担心列表中不必要的最后逗号.(我一直误解了具有严格 C89 编译器的枚举的问题,如 Is the last comma in C enum?.)

Edit: Thank you to Raymond Chen for noting we don't have to worry about the unnecessary final comma in the list. (I had been misremenbering the problem for enums with strict C89 compilers, as in Is the last comma in C enum required?.)

这篇关于计数预处理器宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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