lnlidawei

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

[cpp]:  好玩的“宏定义(macro)”

 

 

 

 

一、有趣的“宏定义”

 

  1、思想/原理:用【宏macro】,定义【伪指令directive】。

 

  2、命令格式:  #define   [directive_name]  [function or ...]

 

  3、应用实例:

1 // directive entry
2 #define __main_begin    int main(int argc, char * argv[], char *envp[]){     // entry first part
3 #define __main_end      ; return 0; }   // entry second part

 

 

 

 

二、源程序

 1 #include <iostream>
 2 
 3 
 4 // directive counter
 5 int icount = 0;
 6 
 7 
 8 // directive entry
 9 #define __main_begin        int main(int argc, char * argv[], char *envp[]){     // entry first part
10 #define __main_end      ; return 0; }   // entry second part
11 
12 
13 // initialize value of 'icount'; or reset value of 'icount';
14 #define __big_begin     big_begin();
15 #define __big_end       big_end();
16 
17 
18 // directives to be ran
19 #define __cmd       big();
20 
21 
22 // function big
23 void big()
24 {
25     icount++;
26     std::cout << "\t[os] big(" << icount << ")" << std::endl;
27 }
28 
29 
30 // initial directive counter
31 void big_begin()
32 {
33     icount = 0;
34     std::cout << "[os] big_begin::set_icount := " <<  icount << std::endl;
35 }
36 
37 
38 // resetting directive counter
39 void big_end()
40 {
41     icount = 0;
42     std::cout << "[os] big_end::set_icount := " <<  icount << std::endl;
43 }
44 
45 
46 // old entry of the program
47 /*
48 int main()
49 {
50     __cmd
51     __cmd
52 
53 }
54 */
55 
56 
57 __main_begin
58 
59     __big_begin
60     
61         __cmd
62         __cmd
63         __cmd
64         
65     __big_end
66     
67 __main_end

 

 

 

 

三、运行结果

1 g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
2 
3 
4 [os] big_begin::set_icount := 0
5     [os] big(1)
6     [os] big(2)
7     [os] big(3)
8 [os] big_end::set_icount := 0

 

 

 

 

四、参考资料

 

  1、无

 

 

  

posted on 2024-01-17 00:55  lnlidawei  阅读(15)  评论(0编辑  收藏  举报