I want to trace logs using a Macro multi parameter always null. problem c++ windows

半腔热情 提交于 2020-01-04 02:47:10

问题


I am using the following way to cout a function's 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 a self destructor,which will cout life time of its own and print szMessageBuffer. However when I use the macro this :

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

The message generated always is hello->(null)

Can Any one help? Many thanks!


回答1:


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__ is not va_list type, but comma-separated arguments, so you need to use sprintf_s, not vsprintf_s.




回答2:


A different approach to logging is to use streams:

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

You can then say things like:

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



回答3:


Macros are not variadic functions, you don't need to process argument list with va_* functions. Macros just transform the text of the source code.

With that said, your compiler (MSVC I assume) supports variadic 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);


来源:https://stackoverflow.com/questions/3027729/i-want-to-trace-logs-using-a-macro-multi-parameter-always-null-problem-c-wind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!