【问题标题】:String handling inside Preprocessor macro预处理器宏中的字符串处理
【发布时间】:2017-09-18 01:18:38
【问题描述】:

我需要更改宏的实现(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)。 [但使用 printf 在 Def1 中工作正常]

在将“str”传递给 syslog 之前,请建议如何从宏内部的“str”中删除第一个和最后一个大括号。

【问题讨论】:

  • 举个例子你如何调用你的宏,因为这种方法printf str;完全失败了。
  • @tilz0R 在“宏用法:”部分中给出
  • 你好 DYZ 。调用宏时传递括号。
  • 这不可能你直接问什么,但如果你使用局部变量,那么它可以做到。编辑:不,它不能。您的使用失败。
  • 我可以通过任何其他方式在宏中编辑“str”的内容???

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


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 2019-06-21
  • 1970-01-01
  • 2012-07-21
  • 2015-07-31
  • 2011-11-28
  • 1970-01-01
  • 2015-04-15
  • 2011-03-26
相关资源
最近更新 更多