gcc: Variadic Macros
1
1 6.20 Macros with a Variable Number of Arguments.
1 ================================================
1
1 In the ISO C standard of 1999, a macro can be declared to accept a
1 variable number of arguments much as a function can. The syntax for
1 defining the macro is similar to that of a function. Here is an
1 example:
1
1 #define debug(format, ...) fprintf (stderr, format, __VA_ARGS__)
1
1 Here '...' is a "variable argument". In the invocation of such a macro,
1 it represents the zero or more tokens until the closing parenthesis that
1 ends the invocation, including any commas. This set of tokens replaces
1 the identifier '__VA_ARGS__' in the macro body wherever it appears. See
1 the CPP manual for more information.
1
1 GCC has long supported variadic macros, and used a different syntax
1 that allowed you to give a name to the variable arguments just like any
1 other argument. Here is an example:
1
1 #define debug(format, args...) fprintf (stderr, format, args)
1
1 This is in all ways equivalent to the ISO C example above, but arguably
1 more readable and descriptive.
1
1 GNU CPP has two further variadic macro extensions, and permits them to
1 be used with either of the above forms of macro definition.
1
1 In standard C, you are not allowed to leave the variable argument out
1 entirely; but you are allowed to pass an empty argument. For example,
1 this invocation is invalid in ISO C, because there is no comma after the
1 string:
1
1 debug ("A message")
1
1 GNU CPP permits you to completely omit the variable arguments in this
1 way. In the above examples, the compiler would complain, though since
1 the expansion of the macro still has the extra comma after the format
1 string.
1
1 To help solve this problem, CPP behaves specially for variable
1 arguments used with the token paste operator, '##'. If instead you
1 write
1
1 #define debug(format, ...) fprintf (stderr, format, ## __VA_ARGS__)
1
1 and if the variable arguments are omitted or empty, the '##' operator
1 causes the preprocessor to remove the comma before it. If you do
1 provide some variable arguments in your macro invocation, GNU CPP does
1 not complain about the paste operation and instead places the variable
1 arguments after the comma. Just like any other pasted macro argument,
1 these arguments are not macro expanded.
1