I want to track logs using the multi parameter of the macro is always null. windows c ++ problems

I use the following method to disable the function time:

#define TIME_COST(message, ...)\
 char szMessageBuffer[2048] = {0};\
 va_list ArgList;\
 va_start(ArgList, message);\
 vsprintf_s(szMessageBuffer, 2048, message, ArgList);\
 va_end(ArgList); \
 string strMessage(szMessageBuffer);\
 CQLogTimer t(strMessage);

// CQLogTimer is the destructor itself, which will use its own lifetime and print szMessageBuffer. However, when I use a macro, this is:

void fun
{
TIME_COST("hello->%s", filePath);
XXXXXX
}

The created message always welcomes → (null)

Can anyone help? Many thanks!

+3
source share
3 answers

The correct version is:

#define TIME_COST(message, ...)\
 char szMessageBuffer[2048] = {0};\
 sprintf_s(szMessageBuffer, 2048, message, __VA_ARGS__);\
 string strMessage(szMessageBuffer);\
 CQLogTimer t(strMessage);

__VA_ARGS__not a type va_list, but arguments separated by commas, so you need to use sprintf_s, not vsprintf_s.

+3
source

:

#define LOG( msg )     \
  {                    \
     ostringstream os; \
     os << msg;        \
     CDLogTimer( os.str() ); \
  }

, :

LOG( "the value of x is " << x << " and of y is " << y );
+2

Macros are not variational functions, you do not need to process the argument list with functions va_*. Macros simply convert source code.

With that said, your compiler (suppose MSVC) supports variable macros with __VA_ARGS__:

#define TIME_COST(fmt, ...)\
 char szMessageBuffer[2048] = {0};\
 sprintf_s(szMessageBuffer, 2048, fmt, __VA_ARGS__);\
 string strMessage(szMessageBuffer);\
 CQLogTimer t(strMessage);
+1
source

Source: https://habr.com/ru/post/1749709/


All Articles