如何在 C 预处理器中生成唯一值? [英] How can I generate unique values in the C preprocessor?

查看:12
本文介绍了如何在 C 预处理器中生成唯一值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一堆相关的预处理器宏,其中一个生成标签,另一个跳转到.我以这种方式使用它们:

I'm writing a bunch of related preprocessor macros, one of which generates labels which the other one jumps to. I use them in this fashion:

MAKE_FUNNY_JUMPING_LOOP(
  MAKE_LABEL();
  MAKE_LABEL();
)

我需要一些方法来生成唯一标签,每个内部 MAKE_LABEL 调用使用预处理器.我试过使用 __LINE__,但由于我在另一个宏中调用 MAKE_LABEL,它们都有相同的行并且标签会发生冲突.

I need some way to generate unique labels, one for each inner MAKE_LABEL call, with the preprocessor. I've tried using __LINE__, but since I call MAKE_LABEL inside another macro, they all have the same line and the labels collide.

我希望将其扩展为:

MAKE_FUNNY_JUMPING_LOOP(
  my_cool_label_1:  // from first inner macro
  ...
  my_cool_label_2:  // from second inner macro
  ...
)

有没有办法用预处理器生成散列或自增整数?

推荐答案

正如其他人所说,__COUNTER__ 是一种简单但非标准的方法.

As others noted, __COUNTER__ is the easy but nonstandard way of doing this.

如果您需要额外的可移植性,或其他酷炫的预处理器技巧,Boost Preprocessor library(适用于 C 和 C++)将起作用.例如,以下头文件将输出一个唯一的标签,无论它被包含在哪里.

If you need extra portability, or for other cool preprocessor tricks, the Boost Preprocessor library (which works for C as well as C++) will work. For example, the following header file will output a unique label wherever it's included.

#include <boost/preprocessor/arithmetic/inc.hpp>
#include <boost/preprocessor/slot/slot.hpp>

#if !defined(UNIQUE_LABEL)
#define UNIQUE_LABEL
#define BOOST_PP_VALUE 1
#include BOOST_PP_ASSIGN_SLOT(1)
#undef BOOST_PP_VALUE
#else
#define BOOST_PP_VALUE BOOST_PP_INC(BOOST_PP_SLOT(1))
#include BOOST_PP_ASSIGN_SLOT(1)
#undef BOOST_PP_VALUE
#endif


BOOST_PP_CAT(my_cool_label_, BOOST_PP_SLOT(1)):

示例:

int main(int argc, char *argv[]) {
    #include "unique_label.h"
    printf("%x
", 1234);
    #include "unique_label.h"
    printf("%x
", 1234);
    #include "unique_label.h"
    return 0;
}

预处理到

int main(int argc, char *argv[]) {
    my_cool_label_1:
    printf("%x
", 1234);
    my_cool_label_2:
    printf("%x
", 1234);
    my_cool_label_3:
    return 0;
}

这篇关于如何在 C 预处理器中生成唯一值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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