蒙恩
一个睡不醒的老男孩儿

导航

 
 1 Linux内核中有如下两个宏:
 2 #define __stringify_1(x...) #x
 3 #define __stringify(x...)   __stringify_1(x)
 4 
 5 写代码测试如下:
 6 #include<stdio.h>
 7 #include<stdlib.h>
 8 #define test1 "hello world"
 9 #define test2(x) "hello " #x      //hello 后面有一个空格
10 #define test3(x) "hello "#x       //引号和#x之间没有空格
11 #define test4    "hello" "world"  //两个字符串
12 #define test5(x...) #x            
13 #define test6(x) #x
14 #define test7(x...) test8(x)
15 #define test8(a,b) (a+b)
16 
17 
18 #define __stringify_1(x...) #x
19 #define __stringify(x...)   __stringify_1(x)
20 #define FOO1 BAR1
21 #define FOO2 BAR2
22 #define BAR1 AAR1
23 #define BAR2 AAR2
24 int main()
25 {
26     printf("test1=%s\n",test1);
27     printf("test2=%s\n",test2( everyone ));         //everyone前后有空格
28     printf("test3=%s\n",test3( everyone test3));    //everyone和test3之间有空格
29     printf("test4=%s\n",test4);
30     printf("test5=%s\n",test5(hello world));        //一个参数,hello和world中间有空格
31     printf("test5=%s\n",test5(hello,world));    //两个参数
32     printf("test5=%s\n",test5(hello, world));   //,和world之间有空格
33     printf("test5=%s\n",test5( hello, world )); //hello 前和world后有空格
34     printf("test5=%s\n",test5( "hello, world" ));  //一个参数,但是参数用""引起来了
35     //printf("%s\n",test6(hello,world));           //编译报错
36     printf("test6=%s\n",test6(hello world));       //一个参数
37     printf("test7=%d\n",test7(1,2));               //两个参数
38 
39     printf("%s\n",__stringify(FOO1,FOO2));         //两个参数
40     printf("%s\n",test5(FOO1,FOO2));               //两个参数
41     return 0;
42 }            
43 
44 /*结果如下*/
45 test1=hello world              
46 test2=hello everyone           
47 test3=hello everyone test3     
48 test4=helloworld               
49 test5=hello world             
50 test5=hello,world              
51 test5=hello, world            
52 test5=hello, world            
53 test5="hello, world"           
54 test6=hello world
55 test7=3                        
56 AAR1,AAR2
57 FOO1,FOO2
58 
59 /*
60 结论:
61 #define DD(x...)       x    会将x替换成()里面的内容 例如:DD(1,2)展开就是 1,2
62 #define DD(x)         #x    会将DD(aa)展开成字符串"aa"
63 #define DD(x...)      #x    会将()里面的内容展开成字符串,例如:DD(1,2,3) 展开是”1,2,3"
64 #define DD "str1" "str2"    会将DD 展开成"str1str2"
65 所以才有了第55,56,57行的结果,其中第55行和56行对比给出了stringify的用意。
66 */

 

posted on 2018-06-27 22:20  DoOrDie  阅读(318)  评论(0编辑  收藏  举报