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


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

例如:

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

相关内容