【问题标题】:why typedef is used so widely in nginx?为什么 typedef 在 nginx 中使用如此广泛?
【发布时间】:2013-09-06 23:39:56
【问题描述】:

例如有很多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这样的结构名是可以用的,为什么typedefngx_module_t一样呢?这是好设计吗?而且,这样做有什么好处?

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

【问题讨论】:

  • 您不必每次创建变量时都使用 struct 关键字。
  • 你可能想给this question一个阅读。

标签: c nginx typedef


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    看其中一个,定义为:

    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));
    

    为什么好或坏?

    有些人认为typedef for structs 是不必要且令人困惑的,take a look

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2011-02-01
        • 2016-02-12
        • 1970-01-01
        • 2017-03-29
        • 1970-01-01
        • 2017-08-20
        • 1970-01-01
        • 1970-01-01
        • 2010-11-02
        相关资源
        最近更新 更多