Joel C. Salomon
5/17/2011 8:27:00 PM
On May 17, 4:01 pm, "Joel C. Salomon" <joelcsalo...@gmail.com> wrote:
> An advantage of Seeb's suggested version is that you can define the
> macro to work on both these lines:
>
> DEBUGPRINT("foo");
> DEBUGPRINT("%s", "bar");
>
> without using the oh-so-clever PP_NARG hack, and without defining an
> extra function.
>
> You need some extra cleverness to get rid of the need for the explicit
> "\n" this way, though.
I nerd-sniped myself; couldn't stop till I'd solved the problem. Both
versions below my signature; as before, share & enjoy.
--Joel
#include <stdio.h>
#include <stdarg.h>
extern void debug_print(char const *file, long line, char const *func,
char const *fmt, ...)
/* __attribute__((format(printf, 4, 5))) */;
#define debug_print(...) \
debug_print(__FILE__, __LINE__, __func__, __VA_ARGS__)
#define PP_STR_(x) #x
#define PP_STR(x) PP_STR_(x)
#define PP_LOCATION __FILE__ ":" PP_STR(__LINE__) ": "
#define DEBUG_PRINT(...) do { \
fprintf(stderr, PP_LOCATION __VA_ARGS__); \
fprintf(stderr, "\n"); \
} while (0)
int
main(void)
{
debug_print("foo");
debug_print("%s", "bar");
DEBUG_PRINT("foo");
DEBUG_PRINT("%s", "bar");
return 0;
}
void
(debug_print)(char const *file, long line, char const *func,
char const *fmt, ...)
{
fprintf(stderr, "%s:%ld, %s(): ", file, line, func);
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, "\n");
}