18 September 2009

miscellaneous in C


Type int represents a machine's natural word size.

#define abs(x) ((x < 0)? -x : x)

#define offsetof(type, member) ((size_t)&((type *)0)->member)

#define roundup(x, y) (x + (x % y))

#define _THIS_IP_ ({ __here: (unsigned long)&&__here; })

#define swap(a, b) ({typeof(a) __tmp = a; a = b; b = __tmp;})

#define container_of(ptr, type, member) ({ \
(type *)((char *)ptr - offsetof(type, member)); })

#define dprintf(fmt, arg...) printf("%s:%s:%d " fmt "\n", \
__FILE__, __FUNCTION__, __LINE__, ##arg)

typedef unsigned char u8;
typedef unsigned long u32;

#define set(val, addr) (*(volatile u32 *)addr = val)

void wrap_printf(const char *fmt, ...) {
va_list args;

va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
}

Reference:
http://www.linuxjournal.com/article/7269
http://c-faq.com
http://kernelnewbies.org/FAQ/DoWhile0
http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html

No comments:

Post a Comment