用于生成带前缀的宏的宏function(避免字符串化)

背景

我有一个项目,我有两个单独的产品具有几乎相同的宏名称,为此我想创建一个类似宏的函数来快速检索宏的值。 我编写了一个getTranslation宏函数来获取提供给“函数”的文字文本,该函数应该被视为字符串和字符串前缀(如下所示)。


我如何完成获取提供给宏的参数,将它们连接在一起(中间带有下划线),并将该结果视为预处理器宏而不是字符串?


代码清单

 /******************************************************************************* * coconut.h ******************************************************************************/ #define COCONUT (PRODUCT_COCONUT) #define COCONUT_FX_REGISTER (100) #define COCONUT_BASE_REGISTER (101) /******************************************************************************* * pineapple.h ******************************************************************************/ #define PINEAPPLE (PRODUCT_PINEAPPLE) #define PINEAPPLE_FX_REGISTER (200) #define PINEAPPLE_BASE_REGISTER (201) /******************************************************************************* * test.c. ******************************************************************************/ #include  #include "translation.h" #include "coconut.h" int main(void) { int i = getTranslation(FX_REGISTER, COCONUT); printf("Translation:%d.\n", i); return 0; } /******************************************************************************* * translation.h ******************************************************************************/ #define FX_REGISTER (0) #define BASE_REGISTER (1) #define getTranslationInternal(x, y) #y "_" #x #define getTranslation(x, y) getTranslationInternal(x, y) enum Products { PRODUCT_COCONUT = 0, PRODUCT_PINEAPPLE, PRODUCT_MAX, PRODUCT_INVALID = (-1) }; 

编译器警告

 test.c: In function 'main': test.c:10:45: warning: initialization makes integer from pointer without a cast [-Wint-conversion] int i = getTranslation(FX_REGISTER, COCONUT); ^ translation.h:7:39: note: in definition of macro 'getTranslationInternal' #define getTranslationInternal(x, y) #y "_" #x ^ test.c:10:10: note: in expansion of macro 'getTranslation' int i = getTranslation(FX_REGISTER, COCONUT); 

样品运行

 Translation:4195812. 

 #define getTranslationInternal(x, y) y ## _ ## x 

如果你在宏定义周围删除括号,我就会为clang工作。