有没有一种方法可以恢复 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;
编辑:我不想使用#undef
,因为它不会恢复旧的宏。另外,如果你有很多宏,例如在 X 宏列表中使用它们(在常量数组和结构的长重复代码/声明中),如果有很多 #undef
指令。
最佳答案
好吧,我自己研究了一下,找到了 pragmas push_macro
和 pop_macro
,它们由 clang、gcc 和 Visual C++ 支持。我用的是clang,所以用起来没问题。缺点:如果要恢复多个宏,它不会减少行数 1,但它会恢复宏并且可以封装:
#pragma push_macro("size")
#define size (100 / sizeof(size_t))
#pragma pop_macro("size")
注释:
¹ 我定义了多个宏并尝试使用以下命令恢复它们:
#pragma push_macro("size", "key", "name")
// define them all
#pragma pop_macro("size", "key", "name")
但这还没有在编译器中实现。因此,对于每个宏,必须有一个单独的行来执行此操作。
关于c - 恢复定义和宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44441892/