(Apologies for the long title, but I couldn't think of a less specific one which would be clear enough)
I need to pass the name of an (object-like) macro to a nested (function-like) macro, as in the following (trivial) example:
#define ROOT_FUNC(INPUT) int v_ ## INPUT = INPUT
#define CALLER_FUNC(INPUT) ROOT_FUNC(INPUT)
#define INTA 1
#define INTB 2
#define INTC 3
Now, if I write ROOT_FUNC(INTA);
in my code I get an integer variable called v_INTA
with the value 1
. If I define a variable in code, int INTD = 4;
, and then write CALLER_FUNC(INTD);
I end up with an integer variable called v_INTD
with the value 4
.
But if I write CALLER_FUNC(INTA);
I get an integer variable called v_1
with a value of 1
, because INTA
is expanded to 1
at the time CALLER_FUNC
is expanded, before ROOT_FUNC
is expanded (i.e. ROOT_FUNC(1)
is what gets expanded).
If I change line 2 to: #define CALLER_FUNC(INPUT) ROOT_FUNC(#INPUT)
(i.e. stringifying INPUT
), a compiler error occurs because it is being asked to define an integer variable called v_"1"
(an invalid name) and give it the value "1"
(a non-integer value).
I know the preprocessor is fairly primitive, but is there any way of achieving what I'm after?
(Second edit for further clarification, I want CALLER_FUNC(INTA);
to expand first to ROOT_FUNC(INTA);
, then to int v_INTA = 1;
– i.e. I want INTA
to be expanded inside ROOT_FUNC
, rather than outside it. I am looking for an answer in principle, not just any way to change CALLER_FUNC
to produce the result int v_INTA = 1;
, which would be trivial).
P.S.
In case you are wondering, I originally had a use case involving signal handling (e.g. taking macro names like SIGINT
as inputs for nested macros), but got around these limitations by simplifying my structure and abandoning nested macros; hence this question is purely academic.