Linux驱动开发——__stringify

在Linux内核中有一个宏__stringify,在include/linux/stringify.h定义如下:

#ifndef __LINUX_STRINGIFY_H
#define __LINUX_STRINGIFY_H

/* Indirect stringification.  Doing two levels allows the parameter to be a
 * macro itself.  For example, compile with -DFOO=bar, __stringify(FOO)
 * converts to "bar".
 */

#define __stringify_1(x...)    #x
#define __stringify(x...)    __stringify_1(x)

#endif    /* !__LINUX_STRINGIFY_H */

其作用实际上就是 把  x 直接转换为字符串。其返回值就是字符串,而不是变量名。

用法1:

  #define __ATTR(_name,_mode,_show,_store) { /
    .attr = {.name = __stringify(_name), .mode = _mode }, /
    .show = _show,    /
    .store = _store,    /
    }

假设我们这样使用  __ATTR: 

                      __ATTR(var_name, 777,  show_function, store_function)

  那么,实际上 复制给  .attr.name 的值是 "var_name" ,而不是var_name 变量所代表的值。

用法2:将枚举类型转换为字符串

#define WCD_MBHC_STRINGIFY(s)  __stringify(s)

enum wcd_notify_event {
    WCD_EVENT_INVALID,
    /* events for micbias ON and OFF */
    WCD_EVENT_PRE_MICBIAS_2_OFF,
    WCD_EVENT_POST_MICBIAS_2_OFF,
    WCD_EVENT_PRE_MICBIAS_2_ON,
    WCD_EVENT_POST_MICBIAS_2_ON,

static const char *wcd_mbhc_get_event_string(int event)
{
    switch (event) {
    case WCD_EVENT_PRE_MICBIAS_2_OFF:
        return WCD_MBHC_STRINGIFY(WCD_EVENT_PRE_MICBIAS_2_OFF);
    case WCD_EVENT_POST_MICBIAS_2_OFF:
        return WCD_MBHC_STRINGIFY(WCD_EVENT_POST_MICBIAS_2_OFF);
    case WCD_EVENT_PRE_MICBIAS_2_ON:
        return WCD_MBHC_STRINGIFY(WCD_EVENT_PRE_MICBIAS_2_ON);

猜你喜欢

转载自www.linuxidc.com/Linux/2016-09/135383.htm
今日推荐