views:

2839

answers:

8

As far as I know, in gcc you can write something like:

#define DBGPRINT(fmt...) printf(fmt);

Is there a way to do that in VC++?

A: 

Almost. It's uglier than that though (and you probably don't want a trailing semi-colon in the macro itself:

define DBGPRINT( DBGPRINT_ARGS ) printf DBGPRINT_ARGS

To use it: DBGPRINT(("%s\n", "Hello World"));

(was missing a pair of parens).

Not sure why all the negatives, the original question didn't state a version of VC++, and variadic macros aren't supported by all compilers.

kfh
+2  A: 

Yes, you can do this in Visual Studio C++ in versions 2005 and beyond (not sure about VS 2003). Take a look at VA_ARGS. You can basically do something like this:

#define DBGPRINTF(fmt, ...)  printf(fmt, __VA_ARGS__)

and the variable arguments to the macro will get passed to the function provided as '...' args, where you can then us va_args to parse them out.

There can be weird behavior with VA_ARGS and the use of macros. Because VA_ARGS is variable, that means that there can be 0 arguments. That might leave you with trailing commas where you didn't intend.

Mark
A: 

What you're looking for are called variadic macros.

Summary of the link: yes, from VC++ 2005 on up.

A: 

The following should work. (See link to Variadic macros)

(Example below shows a fixed and variable arguments.)

#  define DBGPRINTF(fmt,...) \
    do { \
        printf(fmt, __VA_ARGS__); \
    } while(0)
David Dolson
+3  A: 

Yes but only since VC++ 2005. The syntax for your example would be:

#define DBGPRINT(fmt, ...) printf(fmt, __VA_ARGS__)

A full reference is here.

Gareth Simpson
A: 

Search for "VA_ARGS" and va_list in MSDN!

James
+3  A: 

If you do not want to use non-standard extensions, you've to provide extra brackets:

#define DBGPRINT(args) printf(args);
DBGPRINT(("%s\n", "Hello World"));
yrp
+1  A: 

If you don't actually need any of the features of macros (__FILE__, __LINE__, token-pasting, etc.) you may want to consider writing a variadic function using stdargs.h. Instead of calling printf(), a variadic function can call vprintf() in order to pass along variable argument lists.

bk1e