metablaster
metablaster

Reputation: 2184

Macro function not expanding as expected

EDIT possible duplicate link doesn't help resolve the issue.

Bellow is a minimum compilable code with comments, the problem is that ERR_INFO macro is causing troubles expanding HRESULT˙paramater in macro function LOG_IF_FAILED

I'm sure the problem is trivial but debugging macros is such a nightmare.

#define UNICODE
#include <Windows.h>
#include <comdef.h>
#include <iostream>
#include <cwchar>


void DebugLogTrace(PCTSTR format_string, ...)
{
    // implementation not important
}

// Writes a sprintf-formatted string to the logging file.
#define TRACE(...) DebugLogTrace(__VA_ARGS__)

#ifdef UNICODE
// Show only file name instead of full path wide version
#define FILENAME (std::wcsrchr(TEXT(__FILE__), L'\\') ? std::wcsrchr(TEXT(__FILE__), L'\\') + 1 : TEXT(__FILE__))

// Wide string function name
#define FUNCNAME __FUNCTIONW__

// boilerplate macro
#define ERR_INFO FILENAME, FUNCNAME, __LINE__

// Log HRESULTs if failed.
#define LOG_IF_FAILED(file_name, func_name, line, hr) if (FAILED(hr)) \
    { TRACE(TEXT("%s %s %i %s"), file_name, func_name, line, _com_error(hr).ErrorMessage()); }
#else

// ANSI versions here ...

#endif // UNICODE

int main()
{
    HRESULT hr = CoInitializeEx(nullptr,
        COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

    // Here hr is not inserted into expansion
    // ERR_INFO macro is causing problems somehow
    LOG_IF_FAILED(ERR_INFO, hr);

    // This works however
    LOG_IF_FAILED(FILENAME, FUNCNAME, __LINE__, hr);

    return 0;
}

Upvotes: 0

Views: 410

Answers (1)

HolyBlackCat
HolyBlackCat

Reputation: 96116

LOG_IF_FAILED(ERR_INFO, hr) should cause something along the lines of:
error: macro "LOG_IF_FAILED" requires 4 arguments, but only 2 given.

This can be solved with one more level of indirection.

Rename LOG_IF_FAILED to something else, let's say LOG_IF_FAILED_.
Then add #define LOG_IF_FAILED(...) LOG_IF_FAILED_(__VA_ARGS__).

Edit:

This doesn't work with MSVC preprocessor for some reason. If you're using MSVC, LOG_IF_FAILED should be defined as:

#define EMPTY
#define LOG_IF_FAILED(...) LOG_IF_FAILED_ EMPTY (__VA_ARGS__)

Upvotes: 1

Related Questions