Archived

This topic is now archived and is closed to further replies.

MENTAL

Variable arguments with macros

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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 ]

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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!

Share this post


Link to post
Share on other sites
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 this

void 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.

Share this post


Link to post
Share on other sites