3 ms·
Usually for those situations I just try to pick something that's a little more unique (maybe __bar_args). For things that end up defining globals I've used this
by __david__ 11y ago
Usually for those situations I just try to pick something that's a little more unique (maybe __bar_args). For things that end up defining globals I've used this technique before:
#define CAT2(a,b) a##b
#define CAT(a,b) CAT2(a,b)
#define Unique(symbol) CAT(symbol, __LINE__)
and then use
#define my_useless_macro(value) \
static int Unique(__macro_var_name) = value
…with the (large?) caveat that it won't work if you put 2 on the same line:
my_useless_macro(0); // works
my_useless_macro(1); my_useless_macro(2); // Fails
If you expect to call my_usless_macro() multiple times on a line (hint, macro expansions are always on the same line), then you might put an extra optional parameter in there with __VA_ARGS__, like this:
#define my_useless_macro2(value,...) \
static int Unique(CAT(__macro_var_name, __VA_ARGS__)) = value
and then this will work:
my_useless_macro2(1,a); my_useless_macro2(2,b); // works
#define doubly_useless(a,b) \
my_useless_macro2(a, __1); \
my_useless_macro2(b, __2)
doubly_useless(3,4);
The C preprocessor is a bit of big hacky mess, but you can do some fairly powerful (and often type safe) things with it.
- shiro 11y agoThis is clever. I agree that usually just picking some obscure name would suffice. Fun to know nevertheless.