Kernel's “container_of” - any way to make it ISO conforming?

后端 未结 3 862
眼角桃花
眼角桃花 2020-12-17 14:36

While looking at Linux kernel\'s implementation of doubly linked circular lists, I\'ve found following macro:

#define container_of(ptr, type, member) ({              


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 15:32

    The macro is written the way it is to perfom a type check on ptr. It's possible to use a compound literal instead of the statement expression and fall back to a simple check for pointers instead of using __typeof__ if the compiler is not gcc-compatible:

    #ifdef __GNUC__
    #define member_type(type, member) __typeof__ (((type *)0)->member)
    #else
    #define member_type(type, member) const void
    #endif
    
    #define container_of(ptr, type, member) ((type *)( \
        (char *)(member_type(type, member) *){ ptr } - offsetof(type, member)))
    

提交回复
热议问题