编译器#warning:打印枚举值

Compiler #warning: print enum value

我想将枚举的值打印为 #warning#pragma message。我使用 typedef enum 而不是 #define 值,因为它使编辑更容易,并允许输入函数参数和 return 值。

打印原因:enum 的常量最大值不能超过某个值,但是我不能直接在代码中检查该值,因为它的值是自动递增的:typedef enum {a, b, ... az } mytype_t;.在此示例中,az 必须小于 [any u_int].

我曾尝试根据 this post 对值进行字符串化,但它仅适用于 #define 的值。我尝试了 enum 值的变体,但我无法打印实际值,只能打印它的名称。

有没有办法在编译时打印枚举值(或常量变量)?谢谢。

编辑: 我使用 Microchips XC8 编译器(8 位)和 C99。

正如评论Frankie_C写的,你必须把预处理和加工分类。枚举在预处理后求值,而#define、#pragma、#warning 在预处理时求值

C 标准不提供在预处理器宏或其他编译时方法中报告枚举常量值的方法。但是,可以测试该值是否在所需范围内。

自 C 2011 起,您可以使用 _Static_assert 来测试枚举常量:

enum { a, b, c, d, e };

_Static_assert(e <= 3, "Enumeration constant exceeds 3.");

在C 2011之前,您可以通过多种方式拼凑测试,例如:

enum { a, b, c, d, e };

int FailIfSizeMismatches[1];      // Define array with good size.
int FailIfSizeMismatches[e <= 3]; // Define with conflicting size if test fails.

(在 C++ 中,将 _Static_assert 替换为 static_assert。)