Macro preprocessing

D

dhun

Hi All,
I have a following kind of situation.

#define i(p) p
#define r(x) i(in)##_##x

int main(){
#define in a
int a,a_b;
a = r(b);
#undef in
}

where I need to construct a symbol ab, at the place where code is
executed.

A g++ -E test.c, however insert a space between a and b.

What could be possible solution for this?
 
A

Andrey Vul

Hi All,
I have a following kind of situation.

#define i(p) p
#define r(x) i(in)##_##x

int main(){
#define in a
int a,a_b;
a = r(b);
#undef in

}

where I need to construct a symbol ab, at the place where code is
executed.

A g++ -E test.c, however insert a space between a and b.

What could be possible solution for this?

Premature ## . Create helper macros to redirect the preprocessor until
only the expanded token is pasted.
In this case:
#define s__(x,y) x##y
#define s(x,y) s__(x,y)
#define r(x) s(i(in),s(_,x))

Two things happen here:
1. r is defined as the result of a redirected paste macro.
2. s creates redirection so that results of expansion instead of the
raw tokens are pasted.

The paste operator (##) has a higher precedence than expansion. so you
need to create a paster and a wrapper to allow for expansion before
pasting.
With my modifications, gcc does not warn about invalid tokens.
This warning needs to be taken very seriously though, it shows that
your code is missing something.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,188
Latest member
Crypto TaxSoftware

Latest Threads

Top