Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 297
Robert S. Barnes Avatar asked Oct 19 '25 03:10

Robert S. Barnes


1 Answers

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

like image 106
caf Avatar answered Oct 21 '25 18:10

caf