有没有办法恢复 C 中的宏,以便您可以定义一个新的宏,在该宏的名称下可能已经定义了其他宏,并使用以前的值重新定义它?
这样当新定义的宏被删除并且最终重新定义的宏被重置为之前的状态时?
例子:
// a macro parameter used in a library
#define size 10
#include <library/use_size.h>
//here the command/pragma to save the definitions
#define size (100 / sizeof(size_t))
// some use of size ...
//here the command/pragma to reset the definitions
#include <library/allocator_with_size.h>
#undef size
// use size as a variable name
size_t size = 0;
//...
size += 123;
Run Code Online (Sandbox Code Playgroud)
编辑:我不想使用#undef,因为它不会恢复旧的宏。另外,如果你有很多宏,例如在 X 宏列表中使用它们(在常量数组和结构的长重复代码/声明中),如果有很多#undef指令,它看起来很丑陋。
cmd*_*dLP 10
好吧,我研究了自己并找到了 pragmaspush_macro和pop_macro,由 clang、gcc 和 Visual C++ 支持。我用的是clang,所以用起来没问题。缺点:如果要恢复多个宏\xc2\xb9,它不会减少行数,但它会恢复宏并且可以封装:
#pragma push_macro("size")\n #define size (100 / sizeof(size_t))\n#pragma pop_macro("size")\nRun Code Online (Sandbox Code Playgroud)\n\n笔记:
\n\n\xc2\xb9 我定义了多个宏并尝试使用以下命令恢复它们:
\n\n#pragma push_macro("size", "key", "name")\n // define them all\n#pragma pop_macro("size", "key", "name")\nRun Code Online (Sandbox Code Playgroud)\n\n但这还没有在编译器中实现。因此,对于每个宏,必须有一个单独的行来执行此操作。
\n