-->

Linux Kernel Linked List

2020-07-30 02:57发布

问题:

I'm trying to use the Linux Kernel Linked List implementation but I am unable to compile. I'm following these sources exactly with no results (http://www.roman10.net/linux-kernel-programminglinked-list/ and http://kernelnewbies.org/FAQ/LinkedLists)

The list.h Kernel Macro for LIST_HEAD_INIT is as follows:

#define LIST_HEAD_INIT(name) { &(name), &(name) }


struct Node {
int data;
struct list_head list;
};

struct Node mylinkedlist;
LIST_HEAD_INIT(&mylinkedlist.list);    

void add(){
struct Node first;
first.data = 1;
first.list = LIST_HEAD_INIT(first.list);
list_add_tail(&first->list, &mylinkedlist.list);
return 0;
}

I keep getting: "error: expected identifier or '(' before '{'"

回答1:

You are getting that wrong.
First, your should LIST_HEAD(mylinkedlist), not LIST_HEAD_INIT nor struct Node mylinkedlist.
mylinkedlist should be a standalone head of kernel linked list struct, it's used to link all list_head.

Second, you should INIT_LIST_HEAD(&first.list), this is the way to dynamically assignment; LIST_HEAD_INIT is used when structure is statically created at compile time.

Last, you should list_add_tail(&first.list, &mylinkedlist).

so the complete code should be:

LIST_HEAD(mylinkedlist);

void add(){
  struct Node first;
  first.data = 1;
  INIT_LIST_HEAD(&first.list);
  list_add_tail(&first.list, &mylinkedlist);
}

this code work fine for me.
I suggest you read Linux Kernel Development chapter 6, it explain this very well.