我想保存宏的原始文本值,以便我可以重新定义宏并仍然引用原始值。我的用例涉及到宏的宏,因此我试图保存的值本身仍然是一个宏。我有一个在线解释器尝试的小例子,我从这里复制代码。我知道其他 SO 问题讨论了类似的想法,但我没有找到任何涵盖我的用例的内容。

#include <stdio.h>

#define STR(X) (#X)

#define GLOBAL_INT (3)

// I AM TRYING TO SAVE THE TEXTUAL MACRO CONTENT "GLOBAL_INT" (WITHOUT THE QUOTES)
//  IN ANOTHER MACRO SO THAT I CAN UNDEFINE GIM AND STILL REFER TO GLOBAL_INT

#define GIM (GLOBAL_INT)

#define GIM_SAVE (GIM)
#define GIM_SAVE_STR (STR(GIM))
#define STR_GIM_SAVE (STR(GIM_SAVE))
const char *strGimSave = STR(GIM_SAVE);
const char *gimSaveStr = GIM_SAVE_STR;
const char *strGimSaveM = STR_GIM_SAVE;
const char *gimStr = STR(GIM);

#undef GIM

int main(int argc, char *argv[])
{
    printf("strGimSave=%s\n", strGimSave);
    printf("gimSaveStr=%s\n", gimSaveStr);
    printf("strGimSaveM=%s\n", strGimSaveM);
    printf("gimStr=%s\n", gimStr);

    const char *gim_save = STR(GIM_SAVE);
    const char *gim_save_str = GIM_SAVE_STR;
    const char *str_gim_save = STR_GIM_SAVE;
    printf("\ngim_save=%s\n", gim_save);
    printf("gim_save_str=%s\n", gim_save_str);
    printf("str_gim_save=%s\n", str_gim_save);

    return 0;
}

Same code in online interpreter

编辑:我试图在上面的代码中输出“GLOBAL_INT”。上面的代码输出:
strGimSave=GIM_SAVE
gimSaveStr=GIM
strGimSaveM=GIM_SAVE
gimStr=GIM

gim_save=GIM_SAVE
gim_save_str=GIM
str_gim_save=GIM_SAVE

最佳答案

不可能 。 C/C++ 预处理器仅在求值时扩展宏。没有办法告诉它定义宏来扩展另一个结果。

也就是说,如果您使用正确的 STR 定义,您的示例的第一部分实际上会做您想做的事情:

#include <stdio.h>

// HERE, extra level of indirection
#define STR2(X) (#X)
#define STR(X) STR2(X)

#define GLOBAL_INT (3)

#define GIM (GLOBAL_INT)

#define GIM_SAVE (GIM)
#define GIM_SAVE_STR (STR(GIM))
#define STR_GIM_SAVE (STR(GIM_SAVE))
const char *strGimSave = STR(GIM_SAVE);
const char *gimSaveStr = GIM_SAVE_STR;
const char *strGimSaveM = STR_GIM_SAVE;
const char *gimStr = STR(GIM);

#undef GIM

int main(int argc, char *argv[])
{
    printf("strGimSave=%s\n", strGimSave);
    printf("gimSaveStr=%s\n", gimSaveStr);
    printf("strGimSaveM=%s\n", strGimSaveM);
    printf("gimStr=%s\n", gimStr);

    const char *gim_save = STR(GIM_SAVE);
    const char *gim_save_str = GIM_SAVE_STR;
    const char *str_gim_save = STR_GIM_SAVE;
    printf("\ngim_save=%s\n", gim_save);
    printf("gim_save_str=%s\n", gim_save_str);
    printf("str_gim_save=%s\n", str_gim_save);

    return 0;
}

现在生产
strGimSave=(((3)))
gimSaveStr=((3))
strGimSaveM=(((3)))
gimStr=((3))

gim_save=(GIM)
gim_save_str=GIM
str_gim_save=(GIM)

(见 live on coliru )

正如您所看到的,一旦您使用 #undef GIM,宏就会停止扩展为“3”,但是在定义 GIM 时创建的字符串常量会保留该值。使用您在这些宏中放入的所有括号。

关于c++ - 保存 C++ 预处理器宏的原始值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24892806/

10-11 15:51