在宏中替换#defined值

时间:2013-12-19 14:08:01

标签: c++ visual-c++ visual-studio-2008 c-preprocessor

#define PACKAGE Package123
#define TEST_SUITE_NAME_PACKAGE(Suite,Package) Suite##_##Package
#define TEST_SUITE_NAME(Suite) TEST_SUITE_NAME_PACKAGE(Suite,PACKAGE)
#define SUITE_NAME TEST_SUITE_NAME(UtilitiesTest)

我希望SUITE_NAME评估为UtilitiesTest_Package123,但经过多次变更后,我仍然会UtilitiesTest_PACKAGE

注意:SUITE_NAME将用作标识符,而不是字符串。我和###运算符混在一起,但似乎没什么用。

2 个答案:

答案 0 :(得分:1)

预处理器有时需要数量惊人的间接:

#define PACKAGE Package123
#define PASTE(x,y) x##_##y
#define TEST_SUITE_NAME_PACKAGE(Suite,Package) PASTE(Suite,Package)
#define TEST_SUITE_NAME(Suite) TEST_SUITE_NAME_PACKAGE(Suite,PACKAGE)
#define SUITE_NAME TEST_SUITE_NAME(UtilitiesTest)

对于这种情况,这种PASTE方法是常见的预处理技巧。

答案 1 :(得分:0)

只需添加另一个间接级别

#define PACKAGE Package123
#define TEST_SUITE_NAME_PACKAGE(Suite,Package) Suite##_##Package
#define _TEST_SUITE_NAME_PACKAGE(Suite, PACKAGE) TEST_SUITE_NAME_PACKAGE(Suite,PACKAGE)
#define TEST_SUITE_NAME(Suite) _TEST_SUITE_NAME_PACKAGE(Suite,PACKAGE)
#define SUITE_NAME TEST_SUITE_NAME(UtilitiesTest)