Eli5: Macros

Can someone explain to me like I am five, what is a Macro?

The way I understand it, a Macro is a piece of code that will be replaced at compile time. Let say you have a macro like so :

define UE_LOG(string logger, string severity, string text) {
  // put some super complicated code here to do the logging, using the input params

Then instead to writing all that super complicated code, you just have to invoke UE_LOG with the params.
When you compile that code, the machine code written will be the super complicated code, instead of the code you actually wrote in the .cpp files.

(note that i’m pretty sure macros arn’t defined like I wrote).

Can a c++ guru confirm that please?

Close, it’s not done at compile time since they aren’t c++ code. It’s handled by the preprocessor which will replace instances of the macro with C++ code. A very basic example is a simple constant (which can now be done with code but this is how people used to define constants)

#define MAX_NUMBER 5

int main()
    int x = MAX_NUMBER;

MAX_NUMBER would be replaced with 5 and then it would be compiled. Now of course you would just use const or constexpr. However there are some more advanced things that can be done with macros that can’t be done with the language

Fundamentally you have this correct. C++ code is built in three steps, the preprocessor, the compiler and the linker. The key to marcos is the preprocessor.

The preprocessor goes through all your source files, before compliation, and preforms commands. You are probably familiar with #include, which includes the code from another file, into the current file. These are call preprocessor directives and #define is one that creates marcos.

A macros, is simply a piece of code that is copied into the source file by the preprocessor before the code is compiled. So something like:

#define Square(x) ((x)*(x))

Would then allow you to use the following in your own code:

int a = 5;
int b = Square(a);

The preprocessor would replace the above code as follows before it is compiled:

int a = 5;
int b = (a*a);

Thanks @redtoorange, @DanM for the precisions.

Privacy & Terms