0

Im trying to make my defines can be switched during runtime, so I cant enable/disable printing some info.

I have next files:

  • main.c
  • config.c
  • config.h (included in both c files)

in config.c :

//define DEBUG   // <--------------- COMMENT THIS TO SWITCH PRINT/NOT PRINT

#define PRINTF(fmt, ...)    printf("TAG: " fmt "\n", ## __VA_ARGS__)

#ifdef  DEBUG
#define DPRINTF PRINTF
#else
#define DPRINTF(...)    do {} while (0)
#endif

int foo()
{
   ...
   if(error){
      PRINTF("error happens, code %d", code);
   }
   else{
      DPRINF("all good, all parameters: [%d][%d]", par1, par2);
   }
}

(short explanation: if DEBUG defined then macro DPRINTF will print some info, otherwise do nothing)

What I want is be able to dynamically switch it from main.c somehow, instead of comment / uncomment and recompile program.

So my idea was to set in config.h

extern  uint8_t dbg_status;
#define DGB_ON  (1)
#define DGB_OFF (0)
#define ENABLE_DBG (dbg_status? (DGB_ON) : (DGB_OFF))

And in main.c do something like that:

uint8_t dbg_status;

int main(int argc, char** argv)
{
    // enable debug if run with next argument:
    // program.exe -DEBUG 
    if (!strcmp(argv[1], "-DEBUG"))
    {
        // enable debug prints
        dbg_status= 1;
    }
    else
    {
        // disable debug prints
        dbg_status= 0;
    }
    ...
}

But Im stuck with it now, I dont know what to do next...

Add some additional defines in config.c?

#if (ENABLE_DEBUG)
#define DEBUG
#endif

I feel that Im on right way, but dont see where to move next.

UPD: Original idea from here: Changing a macro at runtime in C

But Im stuck with realization...

Mike
  • 1
  • 1
  • 2
    Macros are not present at run time. They control / are used during compilation. – Weather Vane Feb 20 '20 at 17:51
  • 1
    Macros are expanded when compiling. If you want it to be conditional on a runtime value, it needs to expand into an `if` statement. – Barmar Feb 20 '20 at 17:52

1 Answers1

0

You could use something like this:

int debugflag = 0;
void DPRINTF(char *format, ...) {
        if (!debugflag)
                return;
        va_list ap;
        va_start(ap, format);
        vfprintf(stderr, format, ap);
        va_end(ap);
}

Now you can choose dynamically with the global variable debugflag if you want the debug output or not.

With macros, this is not possible directly, since these are evaluated at compile time and cannot be influenced at runtime directly.

Ctx
  • 18,090
  • 24
  • 36
  • 51
  • Any ways to use DPRINTF with my old prototypes of macro? Its just too many places to edit... so another exampe of this: `PRINTF("%s(%d): failed loading file to buffer", __func__, __LINE__);` Can I use your function with same arguments in my code? – Mike Feb 20 '20 at 18:05
  • Yes, it looks like you could just rename it to `DPRINTF` – Ctx Feb 20 '20 at 18:05
  • Hmm, its says **uninitialized local variable 'ap' used** – Mike Feb 20 '20 at 18:45