正如其他人所指出的,__COUNTER__
是这样做的容易,但非标准的方式。
如果您需要额外的便携性,或者其他很酷的预处理技巧,Boost Preprocessor library(适用于C以及C++)将可以工作。例如,下面的头文件将输出一个唯一的标签,无论它包含在哪里。
#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\n", 1234);
#include "unique_label.h"
printf("%x\n", 1234);
#include "unique_label.h"
return 0;
}
预处理到
int main(int argc, char *argv[]) {
my_cool_label_1:
printf("%x\n", 1234);
my_cool_label_2:
printf("%x\n", 1234);
my_cool_label_3:
return 0;
}
什么编译您使用的? – 2009-07-15 17:41:44
我正在使用ICC(STM原型3.0;基于v11,我认为)。 – 2009-07-15 19:31:20
对于C++:http://stackoverflow.com/questions/9949532/generate-unique-numbers-at-compile-time?lq=1 – 2015-06-21 11:39:29