在 C 预处理器中为自己定义一些东西

Defining something to itself in C preprocessor

我运行进入这些行:

#define bool  bool
#define false false
#define true  true

我不认为我需要说的比 "wtf?" 多,但要清楚一点:为自己定义某物有什么意义?

台词来自clang stdbool.h

C 和 C++ 标准明确允许(并要求没有无限扩展)

顺便说一句,类似函数的递归(或self-refential)宏更有用:

#define puts(X) (nblines++,puts(X))

(内部puts是对标准puts函数的调用;宏"overloads"通过计数nblines进一步调用)

您的定义可能会有用,例如对于后来的结构,如 #ifdef true,它不能是一个简单的 #define true,因为那会 "erase" 每次进一步使用 true , 所以它必须正好是 #define true true.

它允许用户代码根据这些宏是否定义进行有条件地编译:

#if defined(bool)
    /*...*/
#else
    /*...*/
#endif

它基本上使您不必用另一个名称(如 HAVE_BOOL)污染全局命名空间,前提是该实现让其用户知道 iff​​ 它提供一个 bool,它还将提供一个扩展到它的同名宏(或者实现可以简单地在内部使用它作为它自己的预处理器条件)。

它被称为自引用宏。

根据gcv参考:

A self-referential macro is one whose name appears in its definition. Recall that all macro definitions are rescanned for more macros to replace. If the self-reference were considered a use of the macro, it would produce an infinitely large expansion. To prevent this, the self-reference is not considered a macro call. It is passed into the preprocessor output unchanged.

参考范例:

One common, useful use of self-reference is to create a macro which expands to itself. If you write

#define EPERM EPERM

then the macro EPERM expands to EPERM. Effectively, it is left alone by the preprocessor whenever it’s used in running text. You can tell that it’s a macro with ‘#ifdef’. You might do this if you want to define numeric constants with an enum, but have ‘#ifdef’ be true for each constant.