Expand Macros using MSVC Compiler

Expand Macros using MSVC Compiler

When developing in C or C++, macros defined with #define are powerful tools that can simplify code, improve readability, or enable conditional compilation - but they can also introduce subtle and hard-to-diagnose bugs. Since the preprocessor performs macro substitution before the compiler sees the code, it's often useful to examine the transformed source after preprocessing to understand exactly what the compiler is working with. This tutorial explains how to expand macros using MSVC compiler.

Suppose we have the following code in main.c:

#define SQUARE(x) ((x) * (x))
 
int main() {
    int result = SQUARE(5);
 
    return 0;
}

Use the /P option to tell MSVC to preprocess only and generate a .i file with all macros expanded:

cl /nologo /P main.c

The command will generate main.i file which will look like this:

#line 1 "main.c"

 
int main() {
    int result = ((5) * (5));
 
    return 0;
}

The /P option also works when preprocessing C++ files.

Leave a Comment

Cancel reply

Your email address will not be published.