简体   繁体   English

在struct定义中定义宏

[英]defining macro inside of struct definition

On the definition of the structure below, there is a line with a macro definition ( #define ). 在下面结构的定义中,有一条带有宏定义的行( #define )。 What does that line do exactly? 那条线究竟做了什么? I understand it makes an alias to the first entry of the array h_addr_list , but it still looks weird to me. 我知道它为数组h_addr_list的第一个条目设置了一个别名,但它对我来说仍然很奇怪。 Is h_addr a member of the struct hostent ? h_addr是struct hostent的成员吗? Is this definition only within the scope of the struct? 这个定义只在结构范围内吗?

struct  hostent
{
  char    *h_name;        /* official name of host */
  char    **h_aliases;    /* alias list */
  int     h_addrtype;     /* host address type */
  int     h_length;       /* length of address */
  char    **h_addr_list;  /* list of addresses from name server */
  #define h_addr  h_addr_list[0]  /* address, for backward compatiblity */
};

The macro definition is not scoped at all, it would work the same way if it was defined outside that struct. 宏定义根本没有作用域,如果它在该结构之外定义,它将以相同的方式工作。

It allows old code to continue using hr.h_addr rather than having to be changed to he.h_addr_list[0] (assuming he is a struct hostent ). 它允许旧代码继续使用hr.h_addr而不必更改为he.h_addr_list[0] (假设he是一个struct hostent )。

To clarify, h_addr is not a field of struct hostent . 为了澄清, h_addr不是struct hostent的字段。 That define is processed by the pre-processor , the actual compiler sees an empty line where the #define is. 该定义由预处理器处理 ,实际编译器看到#define所在的空行。
But if a piece of code is written as he.h_addr , the pre-processor will modify it and replace it with he.h_addr_list[0] . 但是如果一段代码写成he.h_addr ,预处理器将修改它并用he.h_addr_list[0]替换它。 That is what the actual compiler will see. 这就是实际编译器将看到的内容。

Pre-processor macros are never scoped: the compiler proper doesn't even see them - it only sees the result of the substitutions, and the pre-processor ignores (is not aware of) scoping entirely. 预处理器宏从不作用域:编译器本身甚至看不到它们 - 它只看到替换的结果,并且预处理器完全忽略(不知道)作用域。

Once defined, a macro identifier remains visible independently of the C scoping rules. 一旦定义,宏标识符将独立于C作用域规则保持可见。 Its scope begins at its definition, until the end of the translation unit or a corresponding #undef directive. 其范围从其定义开始,直到翻译单元结束或相应的#undef指令。

Here, the definition inside the structure is just for readibility; 这里,结构内部的定义只是为了可读性; you can also define your macro after your structure for example: 您也可以在结构后定义宏,例如:

struct hostent
{
  char *h_name;
  char **h_aliases;
  int h_addrtype;
  int h_length;
  char **h_addr_list;
};

#define h_addr  h_addr_list[0]

It isn't a field at all; 它根本不是一个领域; it allows the user to write s.h_addr instead of s.h_addr_list[0] . 它允许用户编写s.h_addr而不是s.h_addr_list[0]

宏定义没有作用域,因此这个宏在看到此定义的编译单元中可见,直到undef h_addr

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

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