Wednesday, May 16, 2018

Pre-processor token concatenation that involves operators

Recently encountered this problem

#define call_fn(var) myfn(mystruct->var)
call_fn(size)

This resulted in an error. (Use gcc -E only to do pre-processing)

error: pasting "->" and "size" does not give a valid preprocessing token
 #define call_fn(var) myfn(mystruct->##var)

Had to search this a bit to find the reason. The reasons that I found are summarized below.

  • Result of token concatenation should result in a single valid token.
    • Here, mystruct->size (the result of operation) is not s single token. It is actually 3 tokens: "mystruct", "->" and "size"
  • gcc is more stringent than VC++ in evaluating this. So, something that works on VC++ might not work here
So, what is the solution?

Imaging you had to do an add macro. What would you have done?

#define ADD(a,b) (a+b)

As I understand, the same principle applies here. This is what I need to do


#define call_fn(var) myfn(mystruct->var)
call_fn(size)
This will give the expected result: (Use gcc -E only to do pre-processing)

myfn(mystruct->size)