2012-07-28 62 views
1

有人可以告訴我,什麼是錯,此代碼:Linux內核container_of宏示例編譯錯誤

#include <stdio.h> 
#include <stdlib.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));}) 
typedef struct _elem { 
     int  a; 
     float b; 
     double c; 
} elem; 

int main(int argc, char **argv) 
{ 
     elem *my_elem = (elem *)malloc(sizeof *elem); 

     my_elem->a = 1; 
     my_elem->b = 2; 
     my_elem->c = 3; 
     elem  *new_elem_a = container_of(&(my_elem->a), struct _elem, int); 
     fprintf(stdout, "container_of(&(my_elem->a), struct _elem, int) = %p", new_elem_a); 

     return 0; 
} 

我編譯時得到這個錯誤:

[email protected]:~$ gcc -Wall container_of_test.c -o container_of_test 
container_of_test.c: In function ‘main’: 
container_of_test.c:16:51: erreur: expected expression before ‘elem’ 
container_of_test.c:21:32: erreur: expected identifier before ‘int’ 
container_of_test.c:21:32: erreur: expected identifier before ‘int’ 

感謝您的幫助。

回答

2

這裏有2個錯誤

  1. 這container_of宏觀預期的最後一個參數是成員名稱。所以它應該是

    elem *new_elem_a = container_of(&(my_elem->a), struct _elem, a);

  2. elem *my_elem = (elem *)malloc(sizeof *elem)

    有錯誤的操作數爲sizeof,它應該是

    elem *my_elem = (elem *)malloc(sizeof *my_elem)

+0

感謝您的回答:) – iPadDevloperJr 2012-07-29 00:04:24