Question

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++?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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"));

What you're looking for are called [variadic macros](http://msdn.microsoft.com/en-us/library/ms177415(VS.80).aspx).

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

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.

For MSVC 7.1 (.NET 2003), this works:

#if defined(DETAILED_DEBUG)
#define DBGPRINT fprintf
#else
__forceinline void __DBGPRINT(...){}
#define DBGPRINT __DBGPRINT
#endif

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)

Search for "VA_ARGS" and va_list in MSDN!

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 // note: do not use '(' & ')'

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top