枚举中这些#define的目的是什么?

时间:2011-12-21 10:51:44

标签: c linux

我在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值?

5 个答案:

答案 0 :(得分:24)

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

答案 1 :(得分:21)

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

答案 2 :(得分:11)

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

例如:

#ifdef DT_UNKNOWN
    // do something
#endif

答案 3 :(得分:7)

我认为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

答案 4 :(得分:0)

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