为什么要在C中定义具有相同名称和内容的宏? [英] Why define a macro with the same name and content in C?

查看:238
本文介绍了为什么要在C中定义具有相同名称和内容的宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Linux内核标头中的if_link.h,它包含以下枚举:

I am looking into if_link.h in the Linux kernel headers and it contains this enum:

enum {
        IFLA_UNSPEC,
        IFLA_ADDRESS,
        IFLA_BROADCAST,
        IFLA_IFNAME,
        IFLA_MTU,
        IFLA_LINK,
        IFLA_QDISC,
        IFLA_STATS,
        IFLA_COST,
#define IFLA_COST IFLA_COST
        IFLA_PRIORITY,
#define IFLA_PRIORITY IFLA_PRIORITY
        IFLA_MASTER,
#define IFLA_MASTER IFLA_MASTER
....
}

定义看起来没用;他们的目的是什么?为什么只有某些项目具有定义?

The defines look useless; what is their purpose? And why do only some of the items have defines?

推荐答案

如Matthew Slattery

As Matthew Slattery mentioned in another answer, the GCC manual has a section, namely §3.10.5 Self-Referential Macros, which describes the possible uses of such macros.

一种可能的用法是在宏扩展成对其自身的调用时避免无限扩展,但这是不鼓励的做法.另一个用途是定义预处理器宏和枚举:

One possible use is to avoid infinite expansion when a macro expands into a call to itself, but this is a discouraged practice. The other use is to define both preprocessor macros and enums:

如果要使用枚举定义数字常量,但每个常量的'#ifdef'为true,则可以执行此操作.

You might do this if you want to define numeric constants with an enum, but have `#ifdef' be true for each constant.

所以这基本上就是

So this is basically what M.M said in the above comment.

此补丁似乎证实了这一点. :

This seems to be confirmed by this patch:

< rant>为什么内核开发人员的行为如此不一致?我很多 偏好的接口,枚举值也作为定义添加到 本身,以使其易于探查 当前的标题集.

<rant> Why do the kernel developers behave so inconsistently? I much prefer interfaces where an enum value is ALSO added as a define to itself, to make it easy to probe which features are available in the current set of headers.

真正令人沮丧的部分是其中的一些枚举值 设置有#define,其中一些没有.

The really frustrating part is the some of the enum values in this set have #defines, and some of them don't.

这篇关于为什么要在C中定义具有相同名称和内容的宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆