The Red Penguin

Macros


Wednesday 29 July 2020

If we dig through the generated files in a JUCE application, we won’t find our familiar
main() function. There is, however, a macro START_JUCE_APPLICATION() at the end of
Main.cpp.

That’s what we refer to as a macro. A macro is a piece of functionality that’s hidden
away by what we call the Preprocessor. The preprocessor runs before the compiler proper,
and for the sake of brevity, sometimes we use macros to generate code for us.
Macros are simple text-substitution routines. For example if we have


#define THE_ANSWER 42

int main()

std::cout << "the answer to the ultimate question of "

<< "life, the universe, and everything is "
<< THE_ANSWER
<< std::endl;
}


What will is that the preprocessor will take this file as input and output something
akin to the version below:


int main()
{
std::cout << "the answer to the ultimate question of "
<< "life, the universe, and everything is "
<< 42
<< std::endl;
}


Notice how the macro THE_ANSWER got removed and all of its occurrences (granted,
there was only one) got replaced with its value.

Some simple expressions can also be evaluated during preprocessor time.