【问题标题】:What is the purpose of a these #define within an enum?枚举中这些#define 的目的是什么?
【发布时间】:2011-12-21 10:51:43
【问题描述】:

我在 linux 头文件 /usr/include/dirent.h 中找到了这段代码:

enum   
  {    
    DT_UNKNOWN = 0,
# define DT_UNKNOWN DT_UNKNOWN
    DT_FIFO = 1,
# define DT_FIFO    DT_FIFO   
    DT_CHR = 2,
# define DT_CHR     DT_CHR
    DT_DIR = 4,
# define DT_DIR     DT_DIR
    DT_BLK = 6,
# define DT_BLK     DT_BLK
    DT_REG = 8,
# define DT_REG     DT_REG
    DT_LNK = 10,
# define DT_LNK     DT_LNK
    DT_SOCK = 12,
# define DT_SOCK    DT_SOCK   
    DT_WHT = 14
# define DT_WHT     DT_WHT
  };   

这个结构是干什么用的? - 为什么要定义一个相同的字符串,然后编译成 int 值?

【问题讨论】:

标签: c linux


【解决方案1】:

除了其他非常好的答案 - 我会选择它们的主要原因 - 如果您尝试重新定义 DT_UNKNOWN,编译器可能会生成警告或错误。

【讨论】:

    【解决方案2】:

    我的猜测是,其他一些代码可以检查这些枚举值中的一个(或多个)是否已使用 #ifdef 定义。

    【讨论】:

    • 两全其美 - 使用 #ifdef 检查定义,但在调试中仍显示为符号名称。
    • 是的,很可能是这样。正如克里斯在对问题的评论中所说的那样,也许它是遗留问题 - 枚举稍后添加,但仍然需要 #ifdef 对它们的能力。
    • +1:这个技巧是 described in gcc's cpp documentation 作为自引用宏的有用用法。
    【解决方案3】:

    我的(未受过教育的)猜测是#define 语句允许条件测试来查看常量是否已定义。

    例如:

    #ifdef DT_UNKNOWN
        // do something
    #endif
    

    【讨论】:

      【解决方案4】:

      我认为 Luchian Grigore 的回答是正确的。

      没有定义的代码:

      #include <stdio.h>
      
      // Defined somewhere in headers
      #define DT_UNKNOWN 0
      
      enum
      {
          DT_UNKNOWN = 0,
          DT_FIFO = 1,
      };
      
      int main(int argc, char **argv)
      {
          printf("DT_UNKNOWN is %d\n", DT_UNKNOWN);
          return 0;
      }
      

      从编译器的输出来看,不清楚为什么 enum 中的某些代码行不想构建:

      alexander@ubuntu-10:~/tmp$ gcc -Wall ./main.c 
      ./main.c:7: error: expected identifier before numeric constant
      

      在我们添加这样的定义之后:

      #include <stdio.h>
      
      // Defined somewhere in headers
      #define DT_UNKNOWN 0
      
      enum
      {
          DT_UNKNOWN = 0,
          # define DT_UNKNOWN DT_UNKNOWN
          DT_FIFO = 1,
          # define DT_FIFO    DT_FIFO
      };
      
      int main(int argc, char **argv)
      {
          printf("DT_UNKNOWN is %d\n", DT_UNKNOWN);
          return 0;
      }
      

      编译器会告诉我们 DT_UNKNOWN 被重新定义了,并且它被重新定义的地方:

      alexander@ubuntu-10:~/tmp$ gcc -Wall ./main2.c 
      ./main2.c:7: error: expected identifier before numeric constant
      ./main2.c:8:1: warning: "DT_UNKNOWN" redefined
      ./main2.c:3:1: warning: this is the location of the previous definition
      

      【讨论】:

        【解决方案5】:

        我在gcc 中使用了-E-dD 参数(以及-fdump-tree-all)来查看预处理器输出,但没有发现任何用处。所以我猜这段代码除了在使用像gdb这样的调试器调试时可能显示符号名称之外没有任何功能。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-12-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-12
          相关资源
          最近更新 更多