简体   繁体   中英

C enum using macros

In glibc source code, I found that some enumeration definitions include macro definitions. For example:

// file: glibc/stdlib/fmtmsg.h
enum
{
  MM_HARD = 0x001,  /* Source of the condition is hardware.  */
#define MM_HARD MM_HARD
  MM_SOFT = 0x002,  /* Source of the condition is software.  */
#define MM_SOFT MM_SOFT
...
};

and

// file: glibc/bits/confname.h
enum
  {
    _PC_LINK_MAX,
#define _PC_LINK_MAX            _PC_LINK_MAX
    _PC_MAX_CANON,
#define _PC_MAX_CANON           _PC_MAX_CANON
    _PC_MAX_INPUT,
#define _PC_MAX_INPUT           _PC_MAX_INPUT
...
}

Since the syntax of the text macro replacement is

#define identifier replacement-list

But in the above example, identifier is the same as replacement-list. what's the point?

EDITED: I tried to search _PC_LINK_MAX with grep -r , here is the result:

bits/confname.h:    _PC_LINK_MAX,
bits/confname.h:#define _PC_LINK_MAX                    _PC_LINK_MAX
ChangeLog.old/ChangeLog.9:      * sysdeps/unix/sysv/linux/alpha/fpathconf.c: Handle _PC_LINK_MAX here.
conform/data/unistd.h-data:constant _PC_LINK_MAX
manual/conf.texi:@item _PC_LINK_MAX
posix/annexc.c:  "_PC_ASYNC_IO", "_PC_CHOWN_RESTRICTED", "_PC_LINK_MAX", "_PC_MAX_CANON",
posix/fpathconf.c:    case _PC_LINK_MAX:
posix/getconf.c:    { "LINK_MAX", _PC_LINK_MAX, PATHCONF },
posix/getconf.c:    { "_POSIX_LINK_MAX", _PC_LINK_MAX, PATHCONF },
sysdeps/posix/fpathconf.c:    case _PC_LINK_MAX:
sysdeps/posix/pathconf.c:    case _PC_LINK_MAX:
sysdeps/unix/sysv/linux/fpathconf.c:    case _PC_LINK_MAX:
sysdeps/unix/sysv/linux/pathconf.c:    case _PC_LINK_MAX:

It's a very common workaround. It allows programmer to use macro directives (especially #if ) to generate the code if type or enum was declared.

In other standard header files you can see

#ifndef _UINT32_T_DECLARED
typedef __uint32_t uint32_t ;
#define _UINT32_T_DECLARED
#endif

Example usage:

#if defined(_UINT32_T_DECLARED)
typedef my32 uint32_t;
#else
typedef my32 unsigned long;
#endif

#ifdef MM_SOFT
myfunc(MM_SOFT);
#else
#error Required enum missing.
#endif

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM