Using macros to convert print statements

115 Views Asked by At

I have multiple uses of one type of debug statement in my code - say DEBUG("abcd"); or DEBUG("abc %d def", val) which get translated and printed to a file.

Now, however I want to convert them all to a different type of logging which requires using a function with declaration like -

WRITE(char *string);

Usage: WRITE(L"abcd") etc.. Because the usage of this debug statement is huge, I am hoping to use macros to convert the same. Can this be done; also given that the DEBUG function used to take in format specifiers too?

2

There are 2 best solutions below

0
On

Maybe you're looking at : #define DEBUG(str,...) WRITE(str,__VA_ARGS__)

0
On

You probably want something like the gnu function

int asprintf(char **strp, const char *fmt, ...);

that is a function that returns an allocated string of sufficiently large size in *strp that holds your printed string. Supposing that your WRITE and DEBUG macros are only used in places where they are used as statements and not inside expressions, you could then do

#define DEBUG(...)              \
do {                            \
  char* strp = 0;               \
  asprintf(&strp, __VA_ARG__);  \
  WRITE(strp);                  \
  free(strp);                   \
} while(0)

If your platform doesn't have asprintf, you probably can come up with an implementation of it that uses snprintf and enlarges the string to be returned as needed.