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);
might print
do_count:counter.c!123 count=456
-
How can I modify the function to print all local variables if caller omits format_string? e.g.
GLOG();might print
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!123As is, this returns an error:
error: expected expression before ‘,’ token
as the
strncatline is simplystrncat(format, , 248);
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:
It is simpler and doesn’t incur any additional runtime overhead since the string is concatenated at compile-time.
Also note that I have used
__func__instead of__FUNCTION__, because the latter is non-standard.