Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why define a macro with the same name and content in C? [duplicate]

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?

like image 282
Zaboj Campula Avatar asked Feb 18 '17 13:02

Zaboj Campula


People also ask

How can we define macro with different values?

The process to redefine a Macro is: Macro must be defined. When, you want to redefine the Macro, first of all, undefined the Macro by using #undef preprocessor directive. And, then define the Macro again by using #define preprocessor directive.

How do you define a macro in C?

A macro is a name given to a block of C statements as a pre-processor directive. Being a pre-processor, the block of code is communicated to the compiler before entering into the actual coding (main () function). A macro is defined with the pre-processor directive.

Which keyword is used to define the macros in C?

Macros using #define A macro is a fragment of code that is given a name. You can define a macro in C using the #define preprocessor directive.


2 Answers

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.

like image 141
coredump Avatar answered Oct 19 '22 01:10

coredump


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

like image 1
msc Avatar answered Oct 19 '22 01:10

msc