Container_of() not compiling

3.2k Views Asked by At

List.h defines a macro called list_entry which is a wrapper for container_of() function. An elegant function, which seems very delicate:

Consider this piece of code:

tmp = list_entry(pos,(struct Order),ord_Queue);

When I compile it using gcc, a constant error of expected expression is popping up.

My structure is defined as:

struct Order
        {
         double idNum;
         char* entryTime;
         char* eventTime;
         struct list_head ord_Queue;
        };

It seems there is a problem with container_of when there are superfluous brackets used in Arg2 and Arg3, and there should be one bracket only for Arg1 courtesy here . I have tried it, but it doesnt work.

Some help would be appreciated.

2

There are 2 best solutions below

1
On

Maybe there is an error in list.h when you copied it from the kernel? (Assuming you are doing a userspace program here.) Because your example code (stripped a little more) does compile with a known-good implementation.

#include <libHX/list.h>
struct order {
        struct HXlist_head ord_queue;
};
int main(void) {
        struct HXlist_head *pos;
        struct order *o = HXlist_entry(pos, struct order, ord_queue);
}
1
On

I believe that you are missing the inclusion of "offsetof" macro as well, which is used by container_of() internally. Try including following code (instead of including whole list.h.

#include <sys/types.h>
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
#define container_of(ptr, type, member) ({                      \
             const typeof( ((type *)0)->member ) *__mptr = (ptr);    \
             (type *)( (char *)__mptr - offsetof(type,member) );})

#define list_entry(ptr, type, member) \
  container_of(ptr, type, member)

struct list_head {
  struct list_head *next, *prev;
};

And there is no need of adding extra parenthesis in 2nd argument, it should work fine without it. I hope this should work.