log library: macro replacement in D

Ben Gardner bengardner.uncrustify at gmail.com
Sat Apr 1 16:30:35 PST 2006


Hi,

I am trying to port a simple log library from C to D.
This library enables me to easily turn on and off printf() statements at
runtime.

The important functionality is reduced to the following:

//// logger.h
extern int gl_log_sev_mask;

static inline int log_active(int sev)
{
   return gl_log_sev_mask & (1 << sev);
}

enum {
   LSYS  = 0,
   LERR  = 1,
   LWARN = 2,
};

#define LOG(sev, args...) \
   do { if (log_active(sev)) { printf(## args); } } while (0)

//// end logger.h


So, this statement:
   LOG(LWARN, "missing symbol: %s\n", symbol);

gets compiled into:
   if (gl_log_sev_mask & 4)
   {
      printf("missing symbol: %s\n", symbol);
   }

The key features here:
  - no functions are called if the log severity is turned off
  - the variable LOG() parameters are not evaluated unless needed

So how do I do this in D?

In particular, there are two main questions:
 1. How do I do inline functions?
 2. How do I replace the LOG macro?

I know I could brute force it:
void LOG(int sev, ...)
{
   if ((gl_log_mask & (1 << sev)) == 0)
      return;

   ... do printf stuff ...
}

But then I lose the efficiency of the macro approach.

Any ideas?

Thanks,
Ben



More information about the Digitalmars-d-learn mailing list