Let's say I have such definition in one of my headers
#define one 1
0) For 'int' values, generally better to use a (dummy) enum, which is
more nicely scoped.
Now, my question is; is there some function or macro which will help me
to retreive name of a defined value as string in standart C?
No.
1) Use Ada and an enumerated type. Ada compilers are required to
provide a standardized (and fairly nice) binding to C. Among other
things it handles converting between C-style strings and Ada-style
(fixed or doped array of char) which may be useful here.
2) If your definitions are all of simple form like your example, write
a tool which scans your applicable header and/or source files and
generates a function which accepts value and returns (pointer to)
string or even an array indexed by value pointing to or containing
string. With good discipline in your source this can be a one-liner in
awk or perl. With make and some other build environments also you can
have your tool automatically (re)executed when (possibly) needed.
3) Force all your definitions to be of simple (enough) form in your
own language from which you automatically derive both C declarations
and/or #define's, and also a the mapping array or function.
4) <*ON*TOPIC> Use the C preprocessor to do #3 by either:
/* mylits.h */
#ifndef ONELIT
#define ONELIT(id,val) enum { id = val };
#endif
ONELIT(one,1)
ONELIT(two,2)
const char * get_mylit (int val) ;
/* mylits.c */
#include "mylits.h" /* for prototype */
const char * get_mylit (int val)
{ switch (val) {
#undef ONELIT
#define ONELIT(id,val) case val : return # id ;
#include "mylits.h" /* for each
default: return "INVALID MYLIT"; /* or perhaps abort() */
}
}
or (if the list is small enough):
/* mylits.h */
#define MYLITS ONELIT(one,1) ONELIT(two,2) /* etc. */
#ifndef ONELIT
#define ONELIT(id,val) enum { id = val };
MYLITS
#endif
/* mylits.c */
#include "mylits.h"
const char * get_mylit (int val)
{ switch (val) {
#undef ONELIT
#define ONELIT(id,val) case val : return # id ;
MYLITS
default: return "INVALID MYLIT"; } }
Aside: I thought I recalled a FAQ answer along the lines of #2-4, but
only found 2.24. At the usual places and
http://c-faq.com/ .
- David.Thompson1 at worldnet.att.net