1

例如,有很多typedefs 到大量结构中ngx_core.h

typedef struct ngx_module_s      ngx_module_t;
typedef struct ngx_conf_s        ngx_conf_t;
typedef struct ngx_cycle_s       ngx_cycle_t;
typedef struct ngx_pool_s        ngx_pool_t;
typedef struct ngx_chain_s       ngx_chain_t;
typedef struct ngx_log_s         ngx_log_t;
typedef struct ngx_array_s       ngx_array_t;
typedef struct ngx_open_file_s   ngx_open_file_t;
typedef struct ngx_command_s     ngx_command_t;
typedef struct ngx_file_s        ngx_file_t;
typedef struct ngx_event_s       ngx_event_t;
typedef struct ngx_event_aio_s   ngx_event_aio_t;
typedef struct ngx_connection_s  ngx_connection_t;

事实上,我知道结构名称如是ngx_module_s可以使用的,为什么typedef它与ngx_module_t?这是好设计吗?而且,这样做有什么好处?

用 C 语言编程时,这是一种好的做法吗?而且,这种做法的名称是什么?为什么是好是坏?

4

3 回答 3

3

看其中一个,定义为:

struct ngx_command_s {
  ngx_str_t             name;
  ngx_uint_t            type;
  char               *(*set)(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
  ngx_uint_t            conf;
  ngx_uint_t            offset;
  void                 *post;
 };

您可以ngx_command_s按如下方式使用:

struct ngx_command_s *x;
x = malloc(sizeof(struct ngx_command_s));

但是当你typedef,你可以避免struct关键字:

typedef struct ngx_command_s ngx_command_t;

ngx_command_t *x;
x = malloc(sizeof(ngx_command_t));

为什么是好是坏?

有些人认为typedeffor structs 是不必要且令人困惑的,看看.

于 2013-09-03T16:50:56.650 回答
3

这是一种常见的做法。每次声明变量时都不必使用 struct 关键字。

于 2013-09-03T16:42:38.110 回答
0

在 C 中,与 C++ 不同,您不能struct直接按名称引用标记,struct必须始终伴随它。这就是使用 的动机typedef,有时也称为类型别名。

一个好处是源代码可以更清晰,因为冗余信息不会使代码混乱。一个缺点是别名隐藏了它的类型(structunionenum或其他类型)。

请注意,_t类型名称的后缀由 POSIX 保留,因此从技术上讲,这违反了 POSIX 标准。

于 2013-09-03T17:03:37.547 回答