Utkarsh Kumar
Utkarsh Kumar

Reputation: 607

Regarding expansion of MACROS during preprocessing

I have an existing MACRO which takes two entities. ROOT_MACRO(x,y)

I want to define 2 new macros like this :- MACRO_1(x,y)= ROOT_MACRO(z,x__y)

Here I want z to be evaluated in preprocessing using MACRO_2 For ex. my cpp file would look something like this :-

MACRO_2(z)

MACRO_1(x,y)==> Should expand to ROOT_MACRO(z,x__y)

//Later on in the .cpp file,

MACRO_2(p)

MACRO_1(x,y)==> Should expand here to ROOT_MACRO(p,x__y)

Is there a way to achieve this ? I hope the question is clear.

Upvotes: 0

Views: 102

Answers (2)

AShelly
AShelly

Reputation: 35540

@davir is right, you can't #define a define. The best you can get with the standard preprocesor is something like this:

#define  M1(x,y) MACRO_BASE(M2, x##__##y)

...
#define M2 z
M1(x,y) //# expands to MACRO_BASE(z,x__y)

...//later
#define M2 p
M1(x,y) //# expands to MACRO_BASE(p,x__y)

If z and p are values of a fixed type, you could get away with something awful like:

#define M2(v) thetype_t current_m2__ = v
#define M1(x,y) MACRO_BASE(current_m2__, x##__##y)

Which could work as long as you always have one and only one call to M2 in the same scope as M1.

But why not just combine the M2 and M1 calls like #define M(v,x,y) MACRO_BASE(v,x##__##y)?

Upvotes: 0

davir
davir

Reputation: 942

If I understand correctly, you want something like the following:

#define MACRO_2(p) #define MACRO_2_DEFINED p
#define MACRO_1(x,y) ROOT_MACRO(MACRO_2_DEFINED,x__y)

But cpp (c pre-processor) works in one-pass, and you can't define a define. What you could do if you are able to change the build system is use m4 before sending the code to cpp. Here is an example using m4:

#define ROOT_MACRO(x,y) This is the root macro with arguments x and y
define(`MACRO_2',`#undef MACRO_2_DEFINED
#define MACRO_2_DEFINED $1')
define(`MACRO_1', `ROOT_MACRO(MACRO_2_DEFINED, $1__$2)')

MACRO_2(z)
MACRO_1(x,y)

MACRO_2(p)
MACRO_1(x,y)

Then running m4 on the file above (e.g. $m4 foo.c) yields:

#define ROOT_MACRO(x,y) This is the root macro with arguments x and y



#undef MACRO_2_DEFINED
#define MACRO_2_DEFINED z
ROOT_MACRO(MACRO_2_DEFINED, x__y)

#undef MACRO_2_DEFINED
#define MACRO_2_DEFINED p
ROOT_MACRO(MACRO_2_DEFINED, x__y)

And running cpp on the code above (e.g. $m4 foo.c | cpp -) yields:

# 1 "<stdin>"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "<stdin>"






This is the root macro with arguments z and x__y



This is the root macro with arguments p and x__y

Upvotes: 1

Related Questions