4.2 Macros with values
In addition to being defined, a macro can also be given a
value. This value is inserted into the source code at each point where
the macro occurs. The following program uses a macro NUM
, to
represent a number which will be printed:
#include <stdio.h>
int
main (void)
{
printf ("Value of NUM is %d\n", NUM);
return 0;
}
Note that macros are not expanded inside strings--only the
occurrence of NUM
outside the string is substituted by the
preprocessor.
To define a macro with a value, the -D
command-line option can
be used in the form -DNAME=VALUE
. For example, the
following command line defines NUM
to be 100 when compiling the
program above:
$ gcc -Wall -DNUM=100 dtestval.c
$ ./a.out
Value of NUM is 100
This example uses a number, but a macro can take values of any form.
Whatever the value of the macro is, it is inserted directly into the
source code at the point where the macro name occurs. For example, the
following definition expands the occurrences of NUM
to 2+2
during preprocessing:
$ gcc -Wall -DNUM="2+2" dtestval.c
$ ./a.out
Value of NUM is 4
After the preprocessor has made the substitution NUM ==>
2+2
this is equivalent to compiling the following program:
#include <stdio.h>
int
main (void)
{
printf ("Value of NUM is %d\n", 2+2);
return 0;
}
Note that it is a good idea to surround macros by parentheses whenever
they are part of an expression. For example, the following program uses
parentheses to ensure the correct precedence for the multiplication
10*NUM
:
#include <stdio.h>
int
main (void)
{
printf ("Ten times NUM is %d\n", 10 * (NUM));
return 0;
}
With these parentheses, it produces the expected result when compiled
with the same command line as above:
$ gcc -Wall -DNUM="2+2" dtestmul10.c
$ ./a.out
Ten times NUM is 40
Without parentheses, the program would produce the value 22
from
the literal form of the expression 10*2+2 = 22
, instead of the
desired value 10*(2+2) = 40
.
When a macro is defined with -D
alone, gcc
uses a default
value of 1
. For example, compiling the original test program
with the option -DNUM
generates an executable which produces the
following output:
$ gcc -Wall -DNUM dtestval.c
$ ./a.out
Value of NUM is 1
A macro can be defined with an empty value using quotes on the command line,
-DNAME=""
. Such a macro is still treated as defined by
conditionals such as #ifdef
, but expands to nothing.
A macro containing quotes can be defined using shell-escaped quote
characters. For example, the command-line option
-DMESSAGE='"Hello, World!"'
defines a macro MESSAGE
which
expands to the sequence of characters "Hello, World!"
. The outer
shell-quotes '...'
protect the C-quotes of the string
"Hello, World!"
. For an explanation of the different types of
quoting and escaping used in the shell see the "GNU Bash
Reference Manual", section Further reading.