www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - log library: macro replacement in D

reply Ben Gardner <bengardner.uncrustify gmail.com> writes:
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
Apr 01 2006
parent Victor Nakoryakov <nail-mail mail.ru> writes:
Ben Gardner wrote:
  > 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.

No, you would not. When you will compile with -inline I guess such trivial function will be inlined.
 Any ideas?
 
 Thanks,
 Ben

-- Victor (aka nail) Nakoryakov nail-mail<at>mail<dot>ru Krasnoznamensk, Moscow, Russia
Apr 02 2006