简体   繁体   English

C 枚举使用宏

[英]C enum using macros

In glibc source code, I found that some enumeration definitions include macro definitions.在glibc源码中,我发现有些枚举定义中包含宏定义。 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:编辑:我尝试使用grep -r搜索 _PC_LINK_MAX ,结果如下:

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.如果声明了类型或枚举,它允许程序员使用宏指令(尤其是#if )来生成代码。

In other standard header files you can see在其他标准 header 文件中,您可以看到

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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