【问题标题】:Print variable names of #define from a header file从头文件中打印#define 的变量名
【发布时间】:2014-10-19 11:17:30
【问题描述】:

第 3 方库在标题中包含已定义状态变量的列表

// <status.h> -- 3rd party header file
#define SUCCESS 0
#define FAILURE 1
#define OUT_OF_MEM 2
// ... and a lot of them ...

// Functions that return the above status
int Send(); 

我想显示状态名称,即那些定义的变量名称

// "main.c"
#include <status.h>
#include <stdio.h>

void printstat(stat)
{  // Print out stat with variable name
   // Example if 0, print "SUCCESS", and so on... 
}

void main()
{   
   int stat = Send();  
   printstat(stat);
}

由于定义状态变量太多,那么有什么简单的方法来做到这一点?

【问题讨论】:

标签: c header


【解决方案1】:

没有“直接”的解决方案。在翻译单元的预处理阶段之后,这些名称就消失了(即替换为它们的值)。最简单的方法是创建字符串文字的附加数组,其中每个元素的索引对应于宏的值。例如:

const char *status_name[] = {"SUCCESS", "FAILURE", "OUT_OF_MEM"};

放置此类数组的最佳位置是头文件本身。请注意,您需要将标头与数组同步。如果它经常更改,那么您可能需要某种自动生成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 2015-10-19
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多