Variable arguments with macros

Started by
3 comments, last by MENTAL 20 years, 6 months ago
Okay, I was wondering if anyone knew how to do variable arguments with macros, so i can do this:

void Log_WriteFull (const char *Filename, const char *Function, const int32 Line, const char *Text, ...);

#define LOG (x, y) Log_WriteFull (__FILE__, __FUNCTION__, __LINE__, x, y)

LOG ("%s %d %s %d", SomeString, SomeInt, SomeOtherString, SomeOtherInt);

and not have it report back that I have too many arguments for the macro. Also, If i do this:

LOG ("This is a log entry with no extra arguments");
it won''t whine at me about not having enough arguments. any ideas?
Advertisement
C89, C++98: no can do.
C99: the extra arguments are placed in the __VA_ARGS__ ''macro''.

Check your compiler documentation to see if variadic macros are supported.

[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Here''s another solution. Klugey, but it works-ish.

const char* globalFile;
const char globalFunction;
int32 globalLine;

void Log_WriteFull (const char *Text, ...); // uses the file, function, and line stored in the global variables

#define LOG (globalFile = __FILE__), (globalFunction = __FUNCTION__), (globalLine = __LINE__), LogWriteFull

LOG ("%s %d %s %d", SomeString, SomeInt, SomeOtherString, SomeOtherInt);


How appropriate. You fight like a cow.
Fruny: yet another reason to add to my "why i should upgrade VC6" list.

I''ve currently got __FUNCTION__ defined as "??" until i get a compiler that supports it!!


sneftel: i think i might actually do that, but have preprocessor that uses __VA_ARGS__ if it detects it

thanks for the replies guys!
Then there''s always the not-really-variable-arguments but still possibly applicable solution I''ve posted before:
#include <sstream>// A logging function that tags a string or a C-style string is probably best for thisvoid Log_WriteFull(const char *File, const char *Func, int32 Line, const char *Text);#define LOG(sstr_args) { \  std::ostringstream sstr; \  sstr << sstr_args; \  Log_WriteFull(__FILE__, __FUNCTION__, __LINE__, sstr.str().c_str()); \}// Example use:int a = 12345;LOG("a: " << a);

Something like that.

This topic is closed to new replies.

Advertisement