Search code examples
cdata-structureslinux-kerneltypeofc89

The Linux Kernel container_of macro and generic containers in C90


Is it possible to implement the container_of macro in pure C90? I'm not sure how to do it as the Kernel implementation depends on GCC Hacks such as the typeof operator.

I'm asking because I would like to implement a generic container in C90 similar to the Kernel's linked list. The actual container I'm thinking of is a sequenced set similar to what you might get from Boost MultiIndex.


Solution

  • The use of typeof in the kernel definition of container_of() is just for compile-time type-checking - it ensures that the passed ptr is really a pointer to the same type as member. It can be modified to be entirely ANSI C at the cost of this type-checking:

    #define container_of(ptr, type, member) ((type *)((char *)ptr - offsetof(type, member)))
    

    (offsetof() is in <stddef.h>)