计数preprocessor宏 [英] Counting preprocessor macros

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

问题描述

我有这样的宏code,这让我来定义一个 C 枚举并使用一个构造字符串列举名称的列表。它prevents我不必重复枚举名称(和大型列表可能引入错误)。

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

,当扩大,应出示:

which, when expanded, should produce:

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

在实现文件中,我有这样的code:

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

,当扩大,生产:

which, when expanded, produces:

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 宏提到,类似的文件宏,但我希望还有一个更标准的方式。

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])

修改:谢谢陈雷蒙德指出为我们不必担心在列表中不必要的最后一个逗号。 (我一直在misremenbering问题进行严格的C89编译器枚举,如是在C枚举最后一个逗号需要?。 )

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?.)

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

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