使用 #define 重新定义 enum 枚举器
我在 C 头文件中发现了一些我不知道其用途的东西。例如,在文件 bits/socket.h
中,有一个枚举类型 enum __socket_type
,但在每个枚举器后面都有一个定义相同的宏。示例:
enum __socket_type
{
SOCK_STREAM = 1,
#define SOCK_STREAM SOCK_STREAM
...
};
我一直无法找出它的用途。请赐教。我什至不知道如何形成正确的问题来查询谷歌或该网站的搜索框。
I have spotted something in C header files what I can't figure out what is for. For example in file bits/socket.h
there is an enumeration type enum __socket_type
, but after every enumerator there is a define macro which defines the same. Example:
enum __socket_type
{
SOCK_STREAM = 1,
#define SOCK_STREAM SOCK_STREAM
...
};
I have been unable to find out what this is for. Please enlighten me. I don't even know how to form right question for querying google nor this site search box.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
预处理器宏永远不会递归扩展,因此这样的#define 所做的就是将名称保留在使用的地方。当您想要进行预处理器功能测试时,这些东西非常有用。
可用于随后有条件地编译一些代码。
编辑:因此,这将更简洁的枚举方法(没有冲突和范围界定的隐式值)与预处理器测试结合起来。
A prepreprocessor macro will never expand recursively, so what such a
#define
does is leave the name in place whereever it is used. Such things are useful when you want to have a preprocessor feature test.can be used to conditionally compile some code afterwards.
Edit: So this combines the cleaner approach of enumerations (implicit values without collisions and scoping) with preprocessor tests.
我唯一能想到的是,因为人们看到一个全大写的常量,比如
NUM_FILES
,他们会认为这是一个宏,并试图这样写:现在通常这会失败,但是如果你编写
#define NUM_FILES NUM_FILES
,它的行为就像预处理器和IDE的宏以及代码本身的枚举。The only thing I can think of is because people see a constant in all-caps, say
NUM_FILES
, they'll think it's a macro and are tempted to write this:Now normally this would fail, but if you write
#define NUM_FILES NUM_FILES
it behaves as a macro for the preprocessor and IDE's and as an enum for the code itself.我怀疑 IDE 或其他工具可以理解符号是以某种方式定义的。
I would suspect it's for IDEs or other tools to understand that a symbol is defined in some way.