4 ms·
Using macro fails if I happen to pass a variable named _args as one of the arguments to bar(). Is there any clever trick to simulate gensym in C macro?
by shiro 11y ago
Using macro fails if I happen to pass a variable named _args as one of the arguments to bar(). Is there any clever trick to simulate gensym in C macro?
- 0x0dea 11y agoThe magic __COUNTER__ macro supported by some compilers can be used to simulate gensym.
- shiro 11y agoThanks. Never realized gcc had it.
- __david__ 11y agoUsually 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.