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

Gra*_*amW 36 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
  };   
Run Code Online (Sandbox Code Playgroud)

这个构造是什么? - 为什么要定义具有相同字符串的东西,然后将其编译为int值?

Luc*_*ore 24

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


Seb*_*n M 21

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

  • +1:这个技巧是[在`gcc`的`cpp`文档中描述的](http://gcc.gnu.org/onlinedocs/gcc-4.6.2/cpp/Self_002dReferential-Macros.html#Self_002dReferential-Macros)作为自引用宏的有用用法. (5认同)
  • 两个世界中最好的 - 用`#ifdef`检查定义,但在调试时仍然显示为符号名称. (3认同)

Cod*_*ray 11

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

例如:

#ifdef DT_UNKNOWN
    // do something
#endif
Run Code Online (Sandbox Code Playgroud)


ale*_*der 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;
}
Run Code Online (Sandbox Code Playgroud)

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

alexander@ubuntu-10:~/tmp$ gcc -Wall ./main.c 
./main.c:7: error: expected identifier before numeric constant
Run Code Online (Sandbox Code Playgroud)

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

编译器会告诉我们重新定义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
Run Code Online (Sandbox Code Playgroud)