C语言最佳实践
上QQ阅读APP看书,第一时间看更新

1.5.1 下画线前缀的使用

下画线前缀的主要作用是防止命名污染,因此对静态变量或局部变量使用下画线前缀并无意义。在实践中,我们经常对非公开的extern类型(也就是全局)的变量或函数使用下画线前缀,例如:

extern size_t __total_mem_use;

为一个变量加上一个或两个下画线符号作为前缀,通常表示这个变量是非公开的外部变量。对于静态变量或局部变量,使用下画线前缀只会给其他程序员造成困扰,因此不建议使用。

另外,在结构体的定义中,可能包括一些隐藏(或者保留内部使用的)成员。对于这些成员,我们也可追加下画线前缀。在下面这个结构体(pcrdr_msg)的对外定义中,就包含这样的4个成员:

/** the renderer message structure */
struct pcrdr_msg
{
    unsigned int            __refcnt;
    purc_atom_t             __origin;
    void                   *__padding1; // reserved for struct list_head
    void                   *__padding2; // reserved for struct list_head
 
    pcrdr_msg_type          type;
    pcrdr_msg_target        target;
    pcrdr_msg_element_type  elementType;
    pcrdr_msg_data_type     dataType;
 
    ...
};

之所以这样做,是因为我们不希望外部模块访问这4个仅供内部模块使用的成员。在内部模块中,我们可通过另一个结构体(pcrdr_msg_hdr)来访问这4个成员,只需要将结构体pcrdr_msg的指针强制转换为结构体pcrdr_msg_hdr的指针即可:

struct list_head {
    struct list_head *next;
    struct list_head *prev;
};
 
/* the header of the struct pcrdr_msg */
struct pcrdr_msg_hdr {
    atomic_uint             refcnt;
    purc_atom_t             origin;
    struct list_head        ln;
};