在调试C语言程序时,有时需要打印宏的名字。可以通过定义宏,宏名字的数组来获得。
例如:
#include <stdio.h>
#define MACRO_STR(x) {x, #x}
typedef struct _macro_str {
int id;
char *name;
}MACRO_STR_T;
typedef enum _color{
RED,
GREEN,
BLUE,
}COLOR;
MACRO_STR_T g_color_str[] ={
MACRO_STR(RED),
MACRO_STR(GREEN),
MACRO_STR(BLUE),
{-1, NULL}
};
static const char * get_macro_name(MACRO_STR_T* table, int id)
{
int i = 0;
while(table[i].id != -1 && table[i].name != NULL){
if(table[i].id == id)
return table[i].name;
i++;
}
return "";
}
static const char * get_color_name(COLOR color)
{
return get_macro_name(g_color_str, color);
}
int main()
{
COLOR color = RED;
printf("The name of color %d is '%s'. \n", color, get_color_name(color));
return 0;
}