c++unreal-engine4fmt

How to setup {fmt} library for Unreal Engine project?


I'm trying to setup fmt for UE4 project, but still getting compiler errors.

Used toolchain: MSVC\14.16.27023

fmt lib is build from source.

I googled this issue and undefined check macro.

#undef check
#include <fmt/format.h>

void test()
{
    auto test = fmt::format("Number is {}", 42);
}

Getting this compiler errors: enter image description here

I tried this defines and this still not compile.

#define FMT_USE_CONSTEXPR 0
#define FMT_HEADER_ONLY

Maybe someone managed use fmt library in Unreal Engine projects and can share some experience?


Solution

  • There is two main problem with integrating {fmt} library in Unreal Engine.

    1. Global define for check macro. Some variables/function inside fmt implementation named "check". So there is a conflict.
    2. Warning as errors enabled by default. So you have either disable this, or suppress specific warnings.

    I ended up with this solution for my UE project. I defined my own header-wrapper

    MyProjectFmt.h

    #pragma once
    
    #define FMT_HEADER_ONLY
    
    #pragma push_macro("check") // memorize current check macro
    #undef check // workaround to compile fmt library with UE's global check macros
    
    #ifdef _MSC_VER
        #pragma warning(push)
        #pragma warning(disable : 4583)
        #pragma warning(disable : 4582)
        #include "ThirdParty/fmt/Public/fmt/format.h"
        #include "ThirdParty/fmt/Public/fmt/xchar.h" // wchar support
        #pragma warning(pop)
    #else
        #include "ThirdParty/fmt/Public/fmt/format.h"
        #include "ThirdParty/fmt/Public/fmt/xchar.h" // wchar support
    #endif
    
    
    #pragma pop_macro("check") // restore check macro
    

    And then use it in your project like this:

    SomeActor.cpp

    #include "MyProjectFmt.h"
    
    void SomeActor::BeginPlay()
    {
        std::string TestOne = fmt::format("Number is {}", 42);
        std::wstring TestTwo = fmt::format(L"Number is {}", 42);
    }
    

    Also, you could create some Macro-wrapper around it to putt all your characters in Unreal Engine's TEXT() macro, or even write custom back_inserter to format characters directly to FString. This is easy to implement, but this is another story.