c - 恢复定义和宏

标签 c c-preprocessor

有没有一种方法可以恢复 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_macropop_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/

相关文章:

检查数组中是否存在char

C++ 专有定义 'unique_bool' 和 'unique_ulong' ,类型转换回 'bool' 和 'ulong'

c - #line 与全局静态范围的关系是什么?

c - 操作 char[] 并将结果包含在头文件中

c - 运行C程序返回-1.#QNAN0而不是存储在浮点变量中的数字

c - 如何等待所有子进程终止并获取每个退出状态

c - 如何从 C 文件中获取完整的汇编代码?

c - 函数在被强制转换两次后对其自身进行强制转换

c - 在 C 中使用 #define 创建数组

c - "invalid use of void expression"