Macro expansion in VC++






4.97/5 (18 votes)
Expanding a macro in VC++
Let us assume for some unknown reason, we have to write a macro [yes, yes, I know Macros are evil and can be substituted by in-line and template function friendlies - but just in case] or say if we are trying to understand an existing macro in some legacy code.
In these situations, it would be nice if we can see how exactly this macro is expanded by the compiler. This tip suggests a way to do so.
Look at this:
//C:\Test\main.cpp
#define SQUARE(A) (A * A)
void main(int argc, char* argv[])
{
int y = 2;
int s = SQUARE(++y); // Due to this the macro expands in a
// different way and we will get abnormal results
// To debug, we have to see how this macro is expanded
// by the compiler
}
We all know that the value of s
will be 16
(rather than 4
). To see how the macro expands,
Go to VS command prompt and enter:
cl /EP C:\Test\main.cpp > C:\Test\macro.txt
This command will expand the macro and dump it in macro.txt. The dump looks like
void main(int argc, char* argv[])
{
int y = 2;
int s = (++y * ++y);
}
See our macro is expanded.
And DO NOT down vote me:
- If you do not like macros (I too hate them, but ....)
- If this is old trick / re-post (I just want to share)