cmacroslinux-kerneldevice-driverkernel

When do you use container_of macro?


I know what the macro does.

In many kernel level codes, it is often used to traverse linked-list.

I want to find other useful cases.
When do you use container_of or CONTAINING_RECORD macro?
When is the macro extremely useful?


Solution

  • container_of allows you to simplify your data structures by omitting pointers to parent structures.

    It's used within the linked list implementation so that the list node can be an element of any structure, and anyone can find the parent structure without carrying around an explicit pointer.

    Another example is struct work_struct. A workqueue work function receives a work_struct as an argument, and it used to have a generic "data" payload. This data value was removed, making the structure smaller, as the work function can call container_of to find its parent structure.