Making something both a C identifier and a string?

OJW picture OJW · Sep 24, 2008 · Viewed 7.9k times · Source

Say you want to generate a matched list of identifiers and strings

enum
{
NAME_ONE,
NAME_TWO,
NAME_THREE
};

myFunction(NAME_ONE, "NAME_ONE");
myFunction(NAME_TWO, "NAME_TWO");
myFunction(NAME_THREE, "NAME_THREE");

..without repeating yourself, and without auto-generating the code, using C/C++ macros

Initial guess:

You could add an #include file containing

myDefine(NAME_ONE)
myDefine(NAME_TWO)
myDefine(NAME_THREE)

Then use it twice like:

#define myDefine(a) a,
enum {
#include "definitions"
}
#undef myDefine

#define myDefine(a) myFunc(a, "a");
#include "definitions"
#undef myDefine

but #define doesn't let you put parameters within a string?

Answer

Kristopher Johnson picture Kristopher Johnson · Sep 24, 2008

For your second #define, you need to use the # preprocessor operator, like this:

#define myDefine(a) myFunc(a, #a);

That converts the argument to a string.