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

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

问题描述

我正在查看 Linux 内核头文件中的 if_link.h,它包含以下枚举:

枚举{国际图联UNSPEC,国际图联地址,国际图联广播,IFLA_IFNAME,国际图联_MTU,国际图联_链接,国际图联_QDISC,国际图联统计数据,国际图联成本,#define IFLA_COST IFLA_COST国际图联优先级,#define IFLA_PRIORITY IFLA_PRIORITY国际图联大师,#define IFLA_MASTER IFLA_MASTER……}

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

解决方案

作为 Matthew Slattery 在另一个答案中提到,GCC手册有一节,即§3.10.5 自引用宏,其中描述了此类宏的可能用途.

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

<块引用>

如果你想用枚举定义数字常量,你可以这样做,但每个常量的 `#ifdef' 为真.

所以这基本上就是 MM在上面的评论中说.

这个补丁似乎证实了这一点:

<块引用><块引用>

<咆哮>为什么内核开发人员的行为如此不一致?我很更喜欢将枚举值也添加为定义的接口本身,以便于探测哪些功能是可用的当前的标题集.

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

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?

解决方案

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:

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> 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.

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天全站免登陆