预处理器宏中的字符串处理
String handling inside Preprocessor macro
我需要更改宏的实现(LOGGING_MACRO)
printf 进入系统日志。
宏用法:
LOGGING_MACRO(5,("Value of x,y=%d,%d\n",x,y));
Def1 :
#define LOGGING_MACRO(loglevel,str) printf str;
Def2 :
#define LOGGING_MACRO(loglevel,str) syslog(loglevel,str);
注意:我无法更改宏格式:(
Def2 抛出错误,因为 syslog 不接受带有前后大括号的 'str'(2nd arg)。 [但在 Def1 中使用 printf 工作正常]
请建议如何在将 'str' 传递给系统日志之前从宏中的 'str' 中删除第一个和最后一个大括号。
下面的示例将在单线程应用程序中工作:
char* custom_log(const char *fmt, ...) {
static char outputString[200]; //Adjust your size for maximal log value
va_list args;
va_start(args, fmt);
vsprintf(outputString, fmt, args);
va_end(args);
return outputString;
}
然后将宏修改为:
#define LOGGING_MACRO(loglevel,str) syslog(loglevel, custom_log str)
请记住,这仅适用于单线程模式,并确保 custom_log
函数在调用 custom_log 函数的位置可见。
对于多线程,你可以这样更新:
#define LOGGING_MACRO(loglevel,str) do {\
mutex_lock(); /*Lock your mutex for debug print*/ \
syslog(loglevel, custom_log str); /*Debug*/ \
mutex_unlock(); /*Unlock mutex*/ \
} while (0)
请记住,您必须根据系统要求编写 mutex_lock
和 mutex_unlock
函数,以仅锁定多线程之间的调试函数。
我需要更改宏的实现(LOGGING_MACRO) printf 进入系统日志。
宏用法:
LOGGING_MACRO(5,("Value of x,y=%d,%d\n",x,y));
Def1 :
#define LOGGING_MACRO(loglevel,str) printf str;
Def2 :
#define LOGGING_MACRO(loglevel,str) syslog(loglevel,str);
注意:我无法更改宏格式:(
Def2 抛出错误,因为 syslog 不接受带有前后大括号的 'str'(2nd arg)。 [但在 Def1 中使用 printf 工作正常]
请建议如何在将 'str' 传递给系统日志之前从宏中的 'str' 中删除第一个和最后一个大括号。
下面的示例将在单线程应用程序中工作:
char* custom_log(const char *fmt, ...) {
static char outputString[200]; //Adjust your size for maximal log value
va_list args;
va_start(args, fmt);
vsprintf(outputString, fmt, args);
va_end(args);
return outputString;
}
然后将宏修改为:
#define LOGGING_MACRO(loglevel,str) syslog(loglevel, custom_log str)
请记住,这仅适用于单线程模式,并确保 custom_log
函数在调用 custom_log 函数的位置可见。
对于多线程,你可以这样更新:
#define LOGGING_MACRO(loglevel,str) do {\
mutex_lock(); /*Lock your mutex for debug print*/ \
syslog(loglevel, custom_log str); /*Debug*/ \
mutex_unlock(); /*Unlock mutex*/ \
} while (0)
请记住,您必须根据系统要求编写 mutex_lock
和 mutex_unlock
函数,以仅锁定多线程之间的调试函数。