gpt4 book ai didi

c++ - 保存 C++ 预处理器宏的原始值

转载 作者:搜寻专家 更新时间:2023-10-31 00:34:59 24 4
gpt4 key购买 nike

我想保存宏的原始文本值,以便我可以重新定义宏并仍然引用原始值。我的用例涉及一个宏到一个宏,因此我要保存的值本身仍然是一个宏。我有一个在线解释器尝试的小例子,我正在从这里复制代码。我知道其他 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com