预处理器宏内的字符串处理

时间:2017-04-21 06:57:11

标签: c string parameter-passing c-preprocessor stringification

我需要更改Macro的实现(LOGGING_MACRO) printf into syslog。

宏用法:

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不接受带有front&的'str'(第2个arg)背部支撑。 [但在Def1中使用printf正常工作]

请建议如何删除第一个&在将'str'传递给syslog之前,最后从宏中的'str'括起来。

1 个答案:

答案 0 :(得分:2)

以下示例适用于单线程应用程序:

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_lockmutex_unlock函数,以便在多线程之间仅锁定调试功能。