3

Here is what I have (message() is a specialized logging function from a third party library):

#define LOG(fmt, ...) message("%s %s(): #fmt", __FILE__, __func__, __VA_ARGS__);

So I want to be able to do things like:

LOG("Hello world")
LOG("Count = %d", count)

And have it expand to:

message("%s %s(): Hello world", __FILE__, __func__);
message("%s %s(): Count = %d", __FILE__, __func__, count);

But the #fmt thing is not working. It does not evaluate to the macro argument and prints as "#fmt". Is it possible to do what I'm trying to do?

Rich
  • 1,165
  • 1
  • 15
  • 29

1 Answers1

5

Don't put #fmt in the quotes. Just use string literal concatenation to join the two literals.

#define LOG(fmt, ...) message("%s %s(): " fmt, __FILE__, __func__, __VA_ARGS__);
Nick
  • 25,026
  • 7
  • 51
  • 83
  • Thanks, this worked, but actually for an unrelated reason my first example doesn't work (LOG("Hello world") i.e. not using any parameter). However there is already good discussion on that topic here: http://stackoverflow.com/questions/3576396/variadic-macros-with-0-arguments-in-c99 – Rich May 11 '12 at 13:26