Expand Macros using gcc or g++ Compiler

Expand Macros using gcc or g++ Compiler

When you're working with C or C++ and using macros (via #define), it can be helpful to see what the preprocessor is actually doing - especially when debugging tricky macro expansions. Macros can behave unexpectedly if you're not careful with parentheses or argument usage. To catch these early, you can view the preprocessed output, where all macros are expanded before actual compilation. This tutorial shows how to expand macros using gcc or g++ compiler.

Let's say you have the following code in main.c:

#define SQUARE(x) ((x) * (x))

int main() {
    int result = SQUARE(5);

    return 0;
}

You can view the expanded version of this file using gcc or g++ compiler with the -E option, which runs only the preprocessor:

gcc -E main.c

This will output the entire preprocessed code (including macro expansions) to the terminal:

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


int main() {
    int result = ((5) * (5));

    return 0;
}

If you want to save the output to a file instead:

gcc -E main.c -o main.i

This creates a file main.i containing the fully expanded code.

Leave a Comment

Cancel reply

Your email address will not be published.