使用宏有效地获取结构成员

efficiently get struct member with macro

我正在实现双链表。我根据 linux kernel list and the macro container_of:

生成以下宏
typedef struct  s_list
{
    struct s_list   *prev;
    struct s_list   *next;
}               t_list;

# define LIST_ENTRY(ptr, type, lst_member) \
                (type*)((char*)ptr - offsetof(type, lst_member))

# define LIST_MEMBER(ptr, type, lst_member, member) \
                *(typeof(&(((type*)0)->member))) \
                    (LIST_ENTRY(ptr, type, lst_member) + offsetof(type, member))

我想知道这些宏的效率如何。我会根据我的结构定义一个新宏来使用 LIST_MEMBER(),例如:

struct  test
{
     void    *ptr;
     t_list  lst;
     double  x;
};

# define TEST_LIST_C2(ptr) LIST_MEMBER(ptr, struct test, list, c2)

我有两个问题:

如 C99 7.17.3 中所述,offsetof() 是一个宏,因此会在编译时求值。 typeof() 是一个 GNU 扩展,但它也是一个宏。宏在编译时(预处理阶段)被替换为它们的值。

所以是的,gcc 将在编译时计算它可以计算的所有内容,并按照您期望的方式减少表达式。