I have a series of #defines from a library file header of this sort:
typedef int Lib_error;
#define LIB_ERROR_A ((Lib_error) 0x0000)
#define LIB_ER
Just generate a table by parsing those defines in some scripting language. Should be easy-ish to translate those defines to the declaration of a constant array of code, string structs which you can then iterate.
Assuming the library doesn't change often, you'll only need to do this once so you don't need to bother much with script corectness etc.
People seem to have mixed feelings about them, but X-macros are one possible solution.
But if you can't change the header, then your only two options (AFAIK) are:
sed
(assuming you're working on Linux).There isn't a simple or automatic way to do it. You have to generate the list of numbers and names yourself, and provide a lookup function to map between number and name.
You might take a look at the ideas in the blog post 'Enums, Strings and Laziness'; it has some ideas that might help you. (That's closely related to the X-Macros at Dr Dobbs mentioned by Oli Charlesworth; the article there claims the technique goes back to the 60s, albeit that it must have been in a language other than C since C didn't exist back then.)
Warning: The below code piece is just a sample. It can be improvised a lot which is for you to do. : )
Define a structure like below:
typedef struct ErrorStorage
{
Lib_error err;
char err_string[100];
}ErrNoStore;
ErrNoStore arrErr[25];
arrErr[0].err = LIB_ERROR_A;
strcpy(arrErr[0].err_string, "LIB_ERROR_A");
/... and so on .../
and later down in the code define a function like this and call it
void display_error(Lib_error errnum)
{
int i = 0;
for(i=0; i<25;i++)
{
if(errnum == arrErr[i].err)
{
printf("%s\n", arrErr[i].err_string);
}
}
}
}