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

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

例如:


  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. }