歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux驅動開發——__stringify

Linux驅動開發——__stringify

日期:2017/3/1 9:11:47   编辑:Linux編程

在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);

Copyright © Linux教程網 All Rights Reserved