fmtlog icon indicating copy to clipboard operation
fmtlog copied to clipboard

Fix undetected block issue in a debug macro

Open JosueGauthier opened this issue 1 year ago • 0 comments

Hello,

I made a small macro to display a debugging log. Except that when you forget to specify the argument after using brackets, it causes an undetected block

Example:

LOG_DEBUG("{}::blabla") -> The code crashes at runtime with no errors or anything.

correct version: LOG_DEBUG("{}::blabla", a.x) ;

# define LOG_DEBUG(...)
    { \
        logd(__VA_ARGS__) ; \N- fmtlog::poll("{}::blabla") ; \N- cpp
        fmtlog::poll() ; \N- \N- \N- \N- \N- \N
    }

Would you have a solution to avoid this kind of error? I looked at static assert when trying to create a template function, but when I don't want to use brackets in my debugging macro, I also get an error at compile time (e.g. LOG_DEBUG("hello"); ) :

#include <stdexcept>

template <typename... Args>
void logDebug(const char* format, const Args&... args)
{
    static_assert(sizeof...(Args) > 0, "Missing argument !") ;

    try {
        logd(format, args...) ;
    } catch (const std::exception& e) {
        loge("Error : {}", e.what()) ;
    }

    fmtlog::poll() ;
}

struct LogDebugWrapper {
    template <typename... Args>
    LogDebugWrapper(const char* format, const Args&... args)
    {
        logDebug(format, args...) ;
    }
} ;

#define LOG_DEBUG(...) LogDebugWrapper(__VA_ARGS__)

Thanks,

JosueGauthier avatar May 23 '23 09:05 JosueGauthier