I would like to change below code:
#ifdef CONSOLE_VERBOSE_DEBUG
printf("this debug error message is printed to the console");
#elseif FILE_VERBOSE_DEBUG
FILE *log = fopen(...);
...
fprintf();
fclose();
#else
((void) 0) // no debugging
into something like
callThePropperDebugFct("message");
and point this one call to functions declared in the properly included header files depending on which DEBUG level is defined
I know it has to do with c polymorphisms and function pointers, but I can not wrap my head around how to do this
log.c filecallThePropperDebugFct macro to call the right functionvoid log_to_console(const char message)
{
printf("%s", message);
}
void log_to_file(const char *name, const char *message)
{
FILE *f = fopen(name, "a");
if (!f) return;
fprintf(f, message);
fclose(f);
}
void log_to_console(const char message);
void log_to_file(const char *name, const char *message);
#ifdef CONSOLE_VERBOSE_DEBUG
#define callThePropperDebugFct(message) log_to_console(message);
#elseif FILE_VERBOSE_DEBUG
#define callThePropperDebugFct(message) log_to_file(LOG_FILE, message)
#else
#define callThePropperDebugFct(message)
#endif
But you can go further with some variadic macros and variable numbers of arguments functions:
#include <stdarg.h>
#include <stdio.h>
void log_to_console(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
//vsnprintf(buffer, sizeof buffe, fmt, args);
vprintf(fmt, args);
va_end(args);
}
void log_to_file(const char *name, const char *fmt, ...)
{
FILE *f = fopen(name, "a");
if (!f) return;
va_list args;
va_start(args, fmt);
vfprintf(f, fmt, args);
va_end(args);
fclose(f);
}
void log_to_console(const char *fmt, ...);
void log_to_file(const char *name, const char *fmt, ...);
#ifdef CONSOLE_VERBOSE_DEBUG
#define callThePropperDebugFct(...) log_to_console("s", __VA_ARGS__)
#elseif FILE_VERBOSE_DEBUG
#define callThePropperDebugFct(...) log_to_file(LOG_FILE, "%s", __VA_ARGS__)
#else
#define callThePropperDebugFct(...)
#endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With