What about:
#define UNSAFE_GET(X) String str_##X = getFunction(#X);
Or, to provide protection against problems with nested macros:
#define STRINGIFY2(x) #x #define STRINGIFY(x) STRINGIFY2(x) #define PASTE2(a, b) a##b #define PASTE(a, b) PASTE2(a, b) #define SAFE_GET(X) String PASTE(str_, X) = getFunction(STRINGIFY(X));
Using:
SAFE_GET(foo)
And this is what compiled:
String str_foo = getFunction("foo");
Key points:
- Use ## to combine macro parameters into one token (token => variable name, etc.)
- And # for formatting a macro parameter (very useful when performing "reflection" in C / C ++)
- Use the prefix for your macros since they are all in the same “namespace” and you don’t need collisions with any other code. (I chose MLV based on your username).
- Wrapper macros help if you insert macros, i.e. call MLV_GET from another macro with different merge / line parameters (according to the comment below, thanks!).
Macke source share