Adding a global macro in C++

Hi everyone!

I’m looking to create a global function-like macro which would be available in all of my source files.

The idea for the macro would be that it handles null checking and logging, so instead of having something like…

void foo()
{
    if (ObjectPtr == nullptr)
    {
        UE_LOG(...);
        return;
    }
    DoSomethingWith(ObjectPtr);
}

… I might be able to replace it with something that looks like this…

void foo()
{
    REQUIRES(ObjectPtr);
    DoSomethingWith(ObjectPtr);
}

The objective of this is to be able to avoid having to include it into every single file, otherwise I would just make a class out of it, or just leave it as it is for now. I’m mainly just interested if it’s something that’s possible to do.

I suspect that I should be adding the macro definition in MyProject.Build.cs using something like

PrivateDefinitions.Add(MYMACRO);

This seems to work just fine for variable macros like if for some reason I wanted to redefine pi

PrivateDefinitions.Add("PI=3.14");

But I’m confused how to do this for a function-like macro.

It’s probably a bad idea to be even doing this in the first place, but I want to know if it can be done!

(post deleted by author)

Definitions only allow name value pairs. They’re used for conditional compilation like this:

#ifdef MY_CUSTOM_DEFINE
    UE_LOG(LogTemp, Log, TEXT("Custom define is enabled!"));
#endif

This would require a definition like this (I don’t think the “=1” is needed):

PublicDefinitions.Add("MY_CUSTOM_DEFINE=1");

But you cannot do function like macros. For that, you need to add them in a header and include it everywhere you want to use it.

If you absolutely want it without adding more includes, you could add it to CoreMinimal.h but you’d need to remember to re-add it every time you upgrade UE versions. This assumes all your headers already include CoreMinimal.h. This is not recommended.