Question

I'm having difficulty expanding an ACE logging macro. This is an elementary problem but I cannot wrap my head around it.

I'm attempting to formulate my own ACE logging macro with variable argument list. My compiler (gcc version 4.4.6 20120305 (Red Hat 4.4.6-4) (GCC)) supports the __VA_ARGS__ standard. My current definition is as follows:

#define ERROR_PREFIX            ACE_TEXT("ERROR (%T)%?%I")
#define ERROR(FMT,...) ACE_DEBUG((LM_ERROR, ACE_TEXT(FMT) __VA_ARGS__))

Which I would like to call via this calling sequence:

ERROR( "This is an example error in file %s\n", errorString.c_str() )

But I end up with the following compile error:

error: expected ‘)’ before ‘errorString’

How best should I modify my macro definition to combat this problem?

Was it helpful?

Solution

I am not familiar with ACE, but it appears that you are looking for the comma-deletion extension:

#define ERROR(FMT, ...) ACE_DEBUG((LM_ERROR, ACE_TEXT(FMT), ##__VA_ARGS__))

As described in the 'Variadic Macros' section of the GNU CPP manual, putting ## in between a comma and __VA_ARGS__ has the special effect of removing the comma if and only if the macro was invoked with zero variable arguments. Thus,

ERROR("This is an example error");
ERROR("This is an example error %s", string);

will respectively expand to

ACE_DEBUG((LM_ERROR, ACE_TEXT("This is an example error")));
ACE_DEBUG((LM_ERROR, ACE_TEXT("This is an example error %s"), string));

which is probably what you want (again, I don't know ACE). Spacing in and around the three-token sequence , ## __VA_ARGS__ does not matter unless you care about portability to very old GCC, as in pre-EGCS.

This feature is a GNU extension, also supported by clang and anything that uses the EDG front end with its GNU compatibility mode enabled. Crucially, it is not supported by Microsoft's compilers as far as I know.

(Since it's almost Christmas, I should also mention that putting spaces on the inside of your parentheses makes the baby Jesus cry.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top