Macro utility for listing

One socket.h header on my Linux system is as follows.

 /* Bits in the FLAGS argument to `send', `recv', et al. */ enum { MSG_OOB = 0x01, /* Process out-of-band data. */ #define MSG_OOB MSG_OOB MSG_PEEK = 0x02, /* Peek at incoming messages. */ #define MSG_PEEK MSG_PEEK MSG_DONTROUTE = 0x04, /* Don't use local routing. */ #define MSG_DONTROUTE MSG_DONTROUTE ... 

The definition of enum is a kind of idiom for creating type-safe-ish constants in C , which the language really treats as compile-time constants.

My question is: what is the purpose of the macros MSG_OOB , MSG_PEEK , ... that expand to themselves?

+12
c c-preprocessor
Feb 18 '14 at 13:28
source share
2 answers

The POSIX standard requires that “symbolic constants”, such as MSG_DONTROUTE , be “object-like macros” rather than enumerated ones. Defining them themselves allows you to use them in the context of an enumeration, and also work correctly with, for example, #ifdef .

From the POSIX standard:

The header should define the following symbolic constants .... MSG_DONTROUTE

and

the symbolic constant ... refers to the symbol of the C preprocessor (also without arguments).

And finally, from the application:

If a constant needs to be a macro, but it is also allowed to be a different type of constant, such as an enumeration constant, for implementations that define it as another type of constant, a macro is usually defined as follows:

#define macro_name macro_name

This allows applications to use #ifdef, etc., to determine if a macro is defined, but the macro is not used in preprocessor #if directives, because the preprocessor will treat the unexpanded word macro_name as null.

+6
Feb 18 '14 at 13:40
source share

The purpose of these definitions is that an application can do something like

 #ifdef MSG_OOB some code here #endif 

macro expansion is not recursive, therefore evaluating the macro MSG_OOB results in the enum constant MSG_OOB with the same name.

In addition, constants declared as enum help, for example, when debugging.

+7
Feb 18 '14 at 1:42 on
source share



All Articles