Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function polymorphisms depending on debug level

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

like image 865
hewi Avatar asked Jun 22 '26 16:06

hewi


1 Answers

  1. Define functions to log your message in some log.c file
  2. Define your callThePropperDebugFct macro to call the right function

log.c

void 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);
}

log.h

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:

log.c

#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);
}

log.h

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
like image 88
Mathieu Avatar answered Jun 24 '26 04:06

Mathieu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!