Variadic Macros - Red Hat ENTERPRISE LINUX 3 - USING CPP Using Instructions

Using cpp, the c preprocessor
Hide thumbs Also See for ENTERPRISE LINUX 3 - USING CPP:
Table of Contents

Advertisement

Chapter 3. Macros
struct command commands[] =
{
{ "quit", quit_command },
{ "help", help_command },
...
};
It would be cleaner not to have to give each command name twice, once in the string constant and
once in the function name. A macro which takes the name of a command as an argument can make
this unnecessary. The string constant can be created with stringification, and the function name by
concatenating the argument with
#define COMMAND(NAME)
struct command commands[] =
{
COMMAND (quit),
COMMAND (help),
...
};

3.6. Variadic Macros

A macro can be declared to accept a variable number of arguments much as a function can. The syntax
for defining the macro is similar to that of a function. Here is an example:
#define eprintf(...) fprintf (stderr, __VA_ARGS__)
This kind of macro is called variadic. When the macro is invoked, all the tokens in its argument list
after the last named argument (this macro has none), including any commas, become the variable
argument. This sequence of tokens replaces the identifier
it appears. Thus, we have this expansion:
eprintf ("%s:%d: ", input_file, lineno)
==>
fprintf (stderr, "%s:%d: ", input_file, lineno)
The variable argument is completely macro-expanded before it is inserted into the macro expansion,
just like an ordinary argument. You may use the
or to paste its leading or trailing token with another token. (But see below for an important special
case for
.)
##
If your macro is complicated, you may want a more descriptive name for the variable argument than
. GNU CPP permits this, as an extension. You may write an argument name immedi-
__VA_ARGS__
ately before the
; that name is used for the variable argument. The
...
be written
#define eprintf(args...) fprintf (stderr, args)
. Here is how it is done:
_command
{ #NAME, NAME ## _command }
and
#
in the macro body wherever
__VA_ARGS__
operators to stringify the variable argument
##
eprintf
19
macro above could

Advertisement

Table of Contents
loading

This manual is also suitable for:

Enterprise linux 3

Table of Contents