在预处理器宏中检测空参数 [英] Detecting null parameter in preprocessor macro
问题描述
我在香草 C 中具有以下宏功能:
I have the following macro function in vanilla C:
#define GLOG(format_string, ...) { \
const char *file = strrchr(__FILE__, '/'); \
char format[256] = "%s:%s!%d\t"; \
strncat(format, format_string, 248); \
strcat(format, "\n"); \
printf(format, __FUNCTION__, file ? file : __FILE__, __LINE__, ##__VA_ARGS__); \
}
这使我可以打印一条调试消息,其中包含当前函数,文件和行号,例如
which lets me print a debug message containing the current function, file and line number, e.g.
GLOG("count=%d", count);
可能打印
do_count:counter.c!123 count=456
-
如果调用者省略format_string,如何修改函数以打印所有局部变量?例如
How can I modify the function to print all local variables if caller omits format_string? e.g.
GLOG();
可能打印
do_count:counter.c!123 count=456, message="Hello world", array=[7, 8] structure={ptr=0xACE0FBA5E, coord={x=9, y=0}}
如果不可能,如何修改它以仅打印当前函数,文件和行号?例如
If that's not possible, how can I modify it to print just the current function, file and line number? e.g.
do_count:counter.c!123
按原样,这将返回错误:
As is, this returns an error:
错误:,"令牌之前的预期表达式
error: expected expression before ‘,’ token
strncat
行很简单
strncat(format, , 248);
推荐答案
首先,似乎无法通过进程本身在运行时检查所有局部变量,因为C没有任何反映方式.
First, inspecting all the local variables at runtime by the process itself seems impossible because C doesn't have any means for reflection.
第二,如果您这样编写日志记录宏,将会更好:
Second, you would be much better off if you wrote the logging macro like that:
#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define GLOGF(fmt, ...) \
printf("%s:%s " fmt "\n", __func__, __FILE__ "!" TOSTRING(__LINE__), ##__VA_ARGS__)
int main (void) {
/* main:test.c!xx count=5 */
GLOGF("count=%d", 5);
/* main:test.c!xx */
GLOGF();
return 0;
}
这很简单,并且由于在编译时将字符串串联在一起,因此不会产生任何额外的运行时开销.
It is simpler and doesn't incur any additional runtime overhead since the string is concatenated at compile-time.
还要注意,我使用了__func__
而不是__FUNCTION__
,因为后者是非标准的.
Also note that I have used __func__
instead of __FUNCTION__
, because the latter is non-standard.
这篇关于在预处理器宏中检测空参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!