歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C語言:運行中獲取宏名字的技巧

C語言:運行中獲取宏名字的技巧

日期:2017/3/1 11:10:42   编辑:Linux編程

在調試C語言程序時,有時需要打印宏的名字。可以通過定義宏,宏名字的數組來獲得。

例如:

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