#define -> string in C++

Humus

Crazy coder
Veteran
If I have a define like for instance this,

#define COUNT 16

and want to create macro in C++ that would return the string of that define, "16" in this case, is this possible to do in any way in C++? I've tried a number of ways with the token pasting operator, stringizing operator etc., but can't get it right. I can get the string of the define as "COUNT", but not the expanded value which I'm interested in.
The whole point is of course so I don't have to update both the int value and a string value when I fiddle around with the count. The string is needed for passing the value down as a #define to a shader.
 
Advanced preprocessor hax0ring...:

count.h:
Code:
ENTRY(COUNT,16)
ENTRY(TEST,2)

main.cpp:
Code:
#include <stdio.h>

enum
{
    #define ENTRY(x,y) x = y,
    #include "count.h"
    #undef ENTRY
};

char* strings[] = {
    #define ENTRY(x,y) #x,
    #include "count.h"
    #undef ENTRY
};

char* values[] = {
    #define ENTRY(x,y) #y,
    #include "count.h"
    #undef ENTRY
};

int main(void)
{
    printf( "%s = %s = %u\n", strings[0], values[0], COUNT );
    printf( "%s = %s = %u\n", strings[1], values[1], TEST );

    return 0;
}

It's not pretty, but it works :)
 
According to the comp.lang.c faq, put these macros in your code:

#define STR(x) #x
#define XSTR(x) STR(x)

STR() will make a string directly from its argument, XSTR() will, to the extent possible, perform macro expansion on its argument before passing its argument to STR(), which seems to be more or less what you want. For example:

#define A 15+2
char *p = STR(A);
char *q = XSTR(A);

will be expanded to

char *p = "A";
char *q = "15+2"

Hope this helps.
 
Thanks both. Scali's method seems a bit too extensive for my taste though. :p Thought I tried arjan's method, but apparently not. Or I simply screwed it up, doesn't sound entirely unlikely either. But it worked out fine, so this does the job:

#define STR(x) #x
#define DEFINE_STR(x) "#define " #x " " STR(x) "\n"

Thanks
 
Back
Top