将定义的表达式作为文本进行比较

Compare defined expressions as text

假设我有一组这样排列的定义:

#define Var0       ((uint32_t)0x00001)
#define Var1       ((uint32_t)0x00002)
#define Var2       ((uint32_t)0x00004)

稍后在代码中我有这个:

#define CurrVar   Var1

当我尝试比较时:

#if (CurrVar != Var1)
   #error "CurrVar" has to be "Var1" for this code to work
#endif

我得到:

error: token is not a valid binary operator in a preprocessor subexpression

我无法更改 VarX 的值,因为它们是库的一部分,但我需要确保在编译时在代码中使用了正确的值。

有没有办法比较这些表达式? 即使它会被作为文本进行比较,像这样:

"((uint32_t)0x00002)" <> "((uint32_t)0x00002)"
or
"Var1" <> "Var1"
etc

您不能在此类操作中使用任何与 C 相关的内容。预处理器不理解转换,也不比较字符串。

https://godbolt.org/z/X2xuPa

#include <stdint.h>

#define V1 1
#define V2 2
#define V3 3

#define CV V1


#if CV==V1
void foo(void)
{
    printf("V1\n");
}
#else
void foo(void)
{
    printf("not V1\n");
}
#endif

int main(void)
{
    foo();
}

使用 _Static_assert,它在 2011 年的标准 C 中:

_Static_assert(CurrVar == Var1, "CurrVar is not equal to Var1.");

如果您必须使用 2011 年之前的 C 实现,一个常见的错误是使用表达式声明数组类型,如果断言失败,该表达式会导致编译器抱怨数组大小:

typedef char CurrVarIsNotEqualToVar1[CurrVar == Var1 ? 1 : -1];