Macro with variable parameter list

84 views
Skip to first unread message

John Vasquez

unread,
Feb 19, 2003, 7:31:03 PM2/19/03
to
Trying to create a macro that has a variable parameter list like
KdPrint.
This doesn't work
#define MyMacro(level, format, ...) DbgPrint(format,a##)

The compiler is bitchin about the dots.

I need to do it this way not the way KdPrint did does. What I'm I
doing wrong.

John

Walter Oney

unread,
Feb 20, 2003, 4:12:21 AM2/20/03
to
John Vasquez wrote:
> Trying to create a macro that has a variable parameter list like
> KdPrint.
> This doesn't work
> #define MyMacro(level, format, ...) DbgPrint(format,a##)

Define the macro this way (look more closely at KdPrint):

#define MyMacro(level, x) DbgPrint x

Call it this way:

MyMacro(42, ("Error %X happened in function %s at line %d", status,
__FILE__, __LINE__));

The entire second argument to MyMacro, including the parentheses,
replaces "x" in the definition, so the compiler sees:

DbgPrint ("Error %X happened in function %s at line %d", status,
__FILE__, __LINE__);

And, of course, the space between DbgPrint (a function) and its argument
list is irrelevant.

--
Walter Oney, Consulting and Training
Basic and Advanced Driver Programming Seminars
Now teaming with John Hyde for USB Device Engineering Seminars
Check out our schedule at http://www.oneysoft.com

Stephan Wolf

unread,
Feb 20, 2003, 5:45:46 AM2/20/03
to
Yes, the double parentheses are the usual way to implement a variable
argument list in a C macro.

Note that AFAIK variable argument lists in macros are not part of any
C (preprocessor) standard I have seen. I know some compilers (more
precisely: preprocessors) support it, though.

Another solution is a little more tricky and does not require the
double parentheses. Here's an excerpt from the MFC in Visual C++:

["...\MFC\Include\AFX.H"]

#ifdef _DEBUG

void AFX_CDECL AfxTrace(LPCTSTR lpszFormat, ...);
#define TRACE ::AfxTrace

#else // _DEBUG

inline void AFX_CDECL AfxTrace(LPCTSTR, ...) { }
#define TRACE 1 ? (void)0 : ::AfxTrace

#endif // !_DEBUG

The TRACE macro can then be used with any number of arguments.

You should of course define your own DEBUG or TRACE macros and not
depend on MFC.

Stephan
---

Reply all
Reply to author
Forward
0 new messages