C语言:运行中获取宏名字的技巧

在调试C语言程序时,有时需要打印宏的名字。可以通过定义宏,宏名字的数组来获得。

例如:


[cpp]  view plain copy
  1. #include <stdio.h>  
  2.   
  3. #define MACRO_STR(x) {x, #x}  //#x即可取到x的整个字符串
  4. //#define MACRO_FUNC(type) {type##_func();}  //用宏连接函数 
  5. //#define MACRO_FUNC(type) {func_##type();}  //用宏连接函数 
  6. typedef struct _macro_str {  
  7.     int id;  
  8.     char *name;  
  9. }MACRO_STR_T;  
  10.   
  11. typedef enum _color{  
  12.     RED,  
  13.     GREEN,  
  14.     BLUE,  
  15. }COLOR;  
  16.   
  17. MACRO_STR_T g_color_str[] ={  
  18.     MACRO_STR(RED),   
  19.     MACRO_STR(GREEN),  
  20.     MACRO_STR(BLUE),  
  21.      
  22.     {-1, NULL}  
  23. };  
  24.   
  25. static const char * get_macro_name(MACRO_STR_T* table, int id)  
  26. {  
  27.     int i = 0;  
  28.   
  29.     while(table[i].id != -1 && table[i].name != NULL){  
  30.         if(table[i].id == id)  
  31.             return table[i].name;  
  32.   
  33.         i++;  
  34.     }  
  35.     return "";  
  36. }  
  37.   
  38. static const char * get_color_name(COLOR color)  
  39. {  
  40.     return get_macro_name(g_color_str, color);  
  41. }  
  42.   
  43. int main()  
  44. {  
  45.     COLOR color = RED;  
  46.       
  47.     printf("The name of color %d is '%s'. \n", color, get_color_name(color));  
  48.     return 0;  
  49. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值