Why define a macro with the same name and content

2020-02-11 22:23发布

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?

2条回答
Anthone
2楼-- · 2020-02-11 22:40

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.

查看更多
够拽才男人
3楼-- · 2020-02-11 22:47

This macros used in IPv4 protocol for provides the ability to create, remove, or get information about a specific network interface. See man page.

查看更多
登录 后发表回答