pr_debug宏的实现的学习

3060阅读 0评论2013-09-04 embeddedlwp
分类:C/C++

首先看下内核中这段代码:
 

<2.6.30-rc4:linux/kernel.h>
/* If you are writing a driver, please use dev_dbg instead */
#if defined(DEBUG)
#define pr_debug(fmt, ...) \
    printk(KERN_DEBUG pr_fmt(fmt), ##__VA_ARGS__)
#elif defined(CONFIG_DYNAMIC_DEBUG)
/* dynamic_pr_debug() uses pr_fmt() internally so we don't need it here */
#define pr_debug(fmt, ...) do { \         《===1*
    dynamic_pr_debug(fmt, ##__VA_ARGS__); \
    } while (0)
#else
#define pr_debug(fmt, ...) \
    ({ if (0) printk(KERN_DEBUG pr_fmt(fmt), ##__VA_ARGS__); 0; })《===2*
#endif

关于这段代码学习两个技巧:

1.do{ func1_call();func2_call(); }while(0);

好处:

    这是个空操作,并且这样编译时不会出现警告。 

    由于使用宏就如同使用函数一般,必须在最后添加一个“;”,即像如下的方法使用:

    pr_debug(“error: write a file.”); 这样宏定义中只能用do{} while(0),而不能直接使用{}来构成一个代码块。     

2.({if (0) func_call(); 0; })

    不可以。因为这样编译时会有警告:变量未使用。

   为了使这个代码段的返回值为0.

    注意:#define swap(a, b) {int tmp; tmp = b; b = a; a = tmp;}

     c=wap(a,b);是没有返回值的,c=0;

   而:#define swap(a, b) ({int tmp; tmp = b; b = a; a = tmp;})

    则c=wap(a,b);是有返回值的,就是{}中最后语句的值,c=a;

 

 

 

上一篇:关于__attribute__((packed))的含义
下一篇:Linux进程管理之SMP负载平衡