【发布时间】:2017-06-08 17:12:25
【问题描述】:
有没有办法在 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 指令,它看起来很丑。
【问题讨论】:
-
#undef怎么样? -
#undef size ....
-
另外,宏没有“先前状态”。它们要么已定义,要么未定义。
-
我知道undef,它的代码非常难读。
-
什么?不,
#undef只删除指定的宏,而不是全部。而且你不能两次定义同一个宏,这是一个错误。当您不再需要宏时,只需执行#undef SIZE。
标签: c c-preprocessor