问题
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++?
回答1:
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.
回答2:
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.
回答3:
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"));
回答4:
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.
回答5:
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.
回答6:
For MSVC 7.1 (.NET 2003), this works:
#if defined(DETAILED_DEBUG)
#define DBGPRINT fprintf
#else
__forceinline void __DBGPRINT(...){}
#define DBGPRINT __DBGPRINT
#endif
回答7:
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)
回答8:
Search for "VA_ARGS" and va_list in MSDN!
回答9:
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.
来源:https://stackoverflow.com/questions/65037/is-there-a-way-to-write-macros-with-a-variable-argument-list-in-visual-c