Reputation: 6084
I have a macro like this.
#define TRACE(fmt, ...) trace(__FILE__, __FUNCTION__, fmt, __VA_ARGS__);
But sometimes I don't want to supply format string. Something like TRACE() should do. Right now, I use
TRACE("%s", "")
Is there any way to simplify?
Upvotes: 1
Views: 132
Reputation: 78903
Adjacent string literals are merged into one single string. So the following should work
#define TRACE(...) trace(__FILE__, __func__, "" __VA_ARGS__)
TRACE();
TRACE("hello");
TRACE("integer %d", 42);
will result in something equivalent to
trace(__FILE__, __func__, "");
trace(__FILE__, __func__, "hello");
trace(__FILE__, __func__, "integer %d", 42);
The only restriction that this has is that the first argument, if any, must really be a string literal. Another char*
object wouldn't work.
(Observe the use of __func__
this one is the predefined identifier for the function name as of the C standard. And the lack of the ;
in the macro to better fit into the usual function call convention in the flow of normal C code.)
Upvotes: 1
Reputation: 145829
What about?
#define TRACE(...) trace(__FILE__, __FUNCTION__, __VA_ARGS__)
TRACE("");
The ...
ellipsis has to replace at least one argument, so if you use the form TRACE(fmt, ...)
you cannot use a single argument when calling TRACE
.
For this reason the form TRACE(...)
is usually preferred over the form TRACE(fmt, ...)
.
Also note that I removed the ;
in your macro definition. It's a bad practice to have it in the definition, the ;
has to be put after the macro call instead. See this CERT document if you want more information: PRE11-C. Do not conclude macro definitions with a semicolon
Upvotes: 3