Container_of()没有编译

时间:2011-02-14 06:40:11

标签: c linux kernel prefetch

List.h定义了一个名为list_entry的宏,它是container_of()函数的包装器。 优雅的功能,看起来非常精致:

考虑这段代码:

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

当我使用gcc编译它时,弹出预期表达式的常量错误。

我的结构定义为:

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

当Arg2和Arg3中使用了多余的括号时,似乎容器有问题,并且只有一个括号仅适用于Arg1礼貌here。我试过了,但它不起作用。

一些帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

从内核复制时,list.h可能存在错误? (假设你在这里做一个用户空间程序。)因为你的示例代码(被剥离了一点)确实用一个已知良好的实现进行编译。

#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 :(得分:2)

我相信你错过了包含“offsetof”宏的内容,这在内部由container_of()使用。尝试包括以下代码(而不是包括整个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;
};

并且不需要在第二个参数中添加额外的括号,没有它就可以正常工作。 我希望这应该有效。