r/C_Programming • u/Salat_Leaf • May 29 '26
Question How do I split macros into another macros?
Suppose you got a macros code like this:
#define CONST_VAL (64)
#define FUNC32(x) // do smth
#define FUNC64(x) // do smth else
In this case CONST_VAL varies on conditions and might be an expression, thus braces for CONST_VAL are necessary. Now we define one macro for unification of FUNC32 and FUNC64 into one function:
#define FUNC(x) FUNC#CONST_VAL(x)
However it's not working because CONST_VAL should be in braces (the preprocessor result is FUNC(64)(x), which is invalid), thus I need a way to split braces from the raw expression in some way to separate a number so the resulting function macro looked like FUNC64(x)
PS. Don't suggest removing the brackets, I know it might be resolved then and there, I need tooling to chop the macros nevertheless for sort of backwards compatibility
6
u/pjl1967 May 30 '26
Here you go:
FYI, for working on or debugging macros,
cdeclcan be quite handy. Given the above:3
u/Axman6 May 29 '26
8
u/brinza888 May 29 '26
You can’t do this since C pre-processor is single-pass.
As I can guess, it will be enough to make decision between FUNC32 and FUNC64 at compile time. So you can use
ifdefdirective.Somewhere before this you can define VAL32 empty macros for FUNC32 behavior and not define it to stay with FUNC64 behavior.
6
u/aalmkainzi May 29 '26
Try this trick:
2
u/SmokeMuch7356 May 29 '26
When you say
CONST_VALmight be an expression, what kind of expression are we talking about? Do you mean something like asizeofexpression (sizeof (int)) or an arithmetic expression (2 * sizeof(int)) or something like that? If so, then trying to append that into a function or macro name is a non-starter, surrounding parens or not (not to mention, you need to use the##operator for token concatenation, not#). This won't work in principle. To make this work at all,CONST_VALhas to be an unbracketed literal or identifier.Hate to say it, but this is going to require either a runtime mapping or a script that builds the function name and writes to a header file that gets
#included in your code.1
u/Key_River7180 May 29 '26
Ok, you could use
##in gcc c0
u/[deleted] May 29 '26
[deleted] — view deleted comment