Skip to content

Instantly share code, notes, and snippets.

@zhangyuchi
Last active August 29, 2015 14:10
Show Gist options
  • Save zhangyuchi/1cabb9acf3f6091eb958 to your computer and use it in GitHub Desktop.
Save zhangyuchi/1cabb9acf3f6091eb958 to your computer and use it in GitHub Desktop.
Tips of Linux C programming
//list define
struct list_head {
struct list_head *next, *prev;
};
#define LIST_HEAD_INIT(name) { &(name), &(name) }
//链表使用者定义:
struct user_t {
data domain;
struct list_head node;
};
struct list_head g_user_list = LIST_HEAD_INIT(g_user_list);
//通过node定位user_t:
#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)); })
struct user_t* next = container_of(&(g_user_list.next->node), struct user_t, node);
//高效地分支判断
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
long __builtin_expect (long EXP, long C)
//汇编实现的原子操作
__asm__ __volatile__(
" lock ;n"
" addl %1,%0 ;n"
: "=m" (my_var) //output
: "ir" (my_int), "m" (my_var) //input
: //modify /* no clobber-list */
);
//0-length array
struct line {
int length;
char content[0];
};
struct line *thisline = (struct line *)malloc (sizeof (struct line) + content_length);
thisline->length = content_length;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment