-
C
语言宏中
和
的用法
在查看
linux
< br>内核源码的过程中,遇到了许多宏,这里面有许多都涉及到
和
,因此,
在网上搜索了一些资料,
整理如下:
一、一般用法
我们使用
#
把宏参数变为一个字符串
,
用
##
把两个宏参数贴合在一起<
/p>
.
用法
:
#
include
#
include
using namespace std;
#define STR(s)
#s
#define
CONS(a,b)
int(a##e##b)
int main()
{
printf(STR(vck));
//
输出字符串
printf(
// 2e3
输出
:2000
return 0;
}
二、当宏参数是另一个宏的时候
<
/p>
需要注意的是凡宏定义里有用
'#'
或<
/p>
'##'
的地方宏参数是不会再展开
.
1,
非
'#'
和
'##'
的情况
#define
TOW
(2)
#define MUL(a,b) (a*b)
printf(
这行的宏会被展开为:
printf(
MUL
里的参数
TOW
会被展开为
(2).
2,
当有
'#'
或
'##'
的时候
#define A
(2)
#define STR(s)
#s
#define CONS(a,b)
int(a##e##b)
printf(
STR(INT_MAX));
// INT_MAX
#
include
这行会被展开为:
printf(
printf(
// compile error
这一行则是:
printf(
< br>INT_MAX
和
A
都不会再被
展开
,
然而解决这个问题的方法很简单
.
加多一层中间转换宏
.
加这层宏的用意是把所有宏的参数在这层里全部展开
,
那么在转换宏里的那一个宏
(_STR)
就能
得到正确的宏
参数
.
#define A
(2)
#define _STR(s)
#s
#define STR(s)
_STR(s)
//
转换宏
#define _CONS(a,b)
int(a##e##b)
#define CONS(a,b)
_CONS(a,b)
//
转换宏
printf(
//
INT_MAX,int
型的最大值,
为一个变量
#
include
输出为
: int max:
0x7fffffff
STR(INT_MAX) -->
_STR(0x7fffffff)
然后再转换成字符串;
printf(
输出为:
200
CONS(A, A)
-->
_CONS((2), (2))
--> int((2)e(2))
三、
'#'
和
'##'
的一些应用特例
1
、合并匿名变量名
#define
___ANONYMOUS1(type, var, line)
type
var##line
#define
__ANONYMOUS0(type, line)
___ANONYMOUS1(type, _anonymous, line)
#define
ANONYMOUS(type)
__ANONYMOUS0(type, __LINE__)
例:
ANONYMOUS(static int);
即
: static int
_anonymous70;
70
表示该行行号;
第一层:
ANONYMOUS(static int);
-->
__ANONYMOUS0(static int, __LINE__);
第二层:
-->
___ANONYMOUS1(static int, _anonymous,
70);
第三层:
-->
static int
_anonymous70;
即每
次只能解开当前层的宏,所以
__LINE__
在第二层才能被
解开;
2
、填充结构
#define
FILL(a)
{a, #a}
enum IDD{OPEN, CLOSE};
typedef struct MSG{
IDD id;
const char * msg;
}MSG;
MSG _msg[] = {FILL(OPEN), FILL(CLOSE)};
-
-
-
-
-
-
-
-
-
上一篇:威图色标
下一篇:AEAS核心高频词汇++