OSDN Git Service

Fix copyrights.
[pf3gnuchains/gcc-fork.git] / gcc / cpp.texi
1 \input texinfo
2 @setfilename cpp.info
3 @settitle The C Preprocessor
4
5 @ifinfo
6 @dircategory Programming
7 @direntry
8 * Cpp: (cpp).                  The GNU C preprocessor.
9 @end direntry
10 @end ifinfo
11
12 @c @smallbook
13 @c @cropmarks
14 @c @finalout
15 @setchapternewpage odd
16 @ifinfo
17 This file documents the GNU C Preprocessor.
18
19 Copyright 1987, 1989, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
20 1999 Free Software Foundation, Inc.
21
22 Permission is granted to make and distribute verbatim copies of
23 this manual provided the copyright notice and this permission notice
24 are preserved on all copies.
25
26 @ignore
27 Permission is granted to process this file through Tex and print the
28 results, provided the printed document carries copying permission
29 notice identical to this one except for the removal of this paragraph
30 (this paragraph not being relevant to the printed manual).
31
32 @end ignore
33 Permission is granted to copy and distribute modified versions of this
34 manual under the conditions for verbatim copying, provided also that
35 the entire resulting derived work is distributed under the terms of a
36 permission notice identical to this one.
37
38 Permission is granted to copy and distribute translations of this manual
39 into another language, under the above conditions for modified versions.
40 @end ifinfo
41
42 @titlepage
43 @c @finalout
44 @title The C Preprocessor
45 @subtitle Last revised May 1999
46 @subtitle for GCC version 2
47 @author Richard M. Stallman
48 @page
49 @vskip 2pc
50 This booklet is eventually intended to form the first chapter of a GNU 
51 C Language manual.
52
53 @vskip 0pt plus 1filll
54 @c man begin COPYRIGHT
55 Copyright @copyright{} 1987, 1989, 1991-1999
56 Free Software Foundation, Inc.
57
58 Permission is granted to make and distribute verbatim copies of
59 this manual provided the copyright notice and this permission notice
60 are preserved on all copies.
61
62 Permission is granted to copy and distribute modified versions of this
63 manual under the conditions for verbatim copying, provided also that
64 the entire resulting derived work is distributed under the terms of a
65 permission notice identical to this one.
66
67 Permission is granted to copy and distribute translations of this manual
68 into another language, under the above conditions for modified versions.
69 @c man end
70 @end titlepage
71 @page
72
73 @node Top, Global Actions,, (DIR)
74 @chapter The C Preprocessor
75 @c man begin DESCRIPTION
76
77 The C preprocessor is a @dfn{macro processor} that is used automatically by
78 the C compiler to transform your program before actual compilation.  It is
79 called a macro processor because it allows you to define @dfn{macros},
80 which are brief abbreviations for longer constructs.
81
82 The C preprocessor provides four separate facilities that you can use as
83 you see fit:
84
85 @itemize @bullet
86 @item
87 Inclusion of header files.  These are files of declarations that can be
88 substituted into your program.
89
90 @item
91 Macro expansion.  You can define @dfn{macros}, which are abbreviations
92 for arbitrary fragments of C code, and then the C preprocessor will
93 replace the macros with their definitions throughout the program.
94
95 @item
96 Conditional compilation.  Using special preprocessing directives, you
97 can include or exclude parts of the program according to various
98 conditions.
99
100 @item
101 Line control.  If you use a program to combine or rearrange source files into
102 an intermediate file which is then compiled, you can use line control
103 to inform the compiler of where each source line originally came from.
104 @end itemize
105
106 C preprocessors vary in some details.  This manual discusses the GNU C
107 preprocessor, the C Compatible Compiler Preprocessor.  The GNU C
108 preprocessor provides a superset of the features of ANSI Standard C@.
109
110 ANSI Standard C requires the rejection of many harmless constructs commonly
111 used by today's C programs.  Such incompatibility would be inconvenient for
112 users, so the GNU C preprocessor is configured to accept these constructs
113 by default.  Strictly speaking, to get ANSI Standard C, you must use the
114 options @samp{-trigraphs}, @samp{-undef} and @samp{-pedantic}, but in
115 practice the consequences of having strict ANSI Standard C make it
116 undesirable to do this.  @xref{Invocation}.
117
118 The C preprocessor is designed for C-like languages; you may run into
119 problems if you apply it to other kinds of languages, because it assumes
120 that it is dealing with C@.  For example, the C preprocessor sometimes
121 outputs extra white space to avoid inadvertent C token concatenation,
122 and this may cause problems with other languages.
123 @c man end
124
125 @menu
126 * Global Actions::    Actions made uniformly on all input files.
127 * Directives::        General syntax of preprocessing directives.
128 * Header Files::      How and why to use header files.
129 * Macros::            How and why to use macros.
130 * Conditionals::      How and why to use conditionals.
131 * Combining Sources:: Use of line control when you combine source files.
132 * Other Directives::  Miscellaneous preprocessing directives.
133 * Output::            Format of output from the C preprocessor.
134 * Invocation::        How to invoke the preprocessor; command options.
135 * Concept Index::     Index of concepts and terms.
136 * Index::             Index of directives, predefined macros and options.
137 @end menu
138
139 @node Global Actions, Directives, Top, Top
140 @section Transformations Made Globally
141
142 Most C preprocessor features are inactive unless you give specific directives
143 to request their use.  (Preprocessing directives are lines starting with
144 @samp{#}; @pxref{Directives}).  But there are three transformations that the
145 preprocessor always makes on all the input it receives, even in the absence
146 of directives.
147
148 @itemize @bullet
149 @item
150 All C comments are replaced with single spaces.
151
152 @item
153 Backslash-Newline sequences are deleted, no matter where.  This
154 feature allows you to break long lines for cosmetic purposes without
155 changing their meaning.
156
157 @item
158 Predefined macro names are replaced with their expansions
159 (@pxref{Predefined}).
160 @end itemize
161
162 The first two transformations are done @emph{before} nearly all other parsing
163 and before preprocessing directives are recognized.  Thus, for example, you
164 can split a line cosmetically with Backslash-Newline anywhere (except
165 when trigraphs are in use; see below).
166
167 @example
168 /*
169 */ # /*
170 */ defi\
171 ne FO\
172 O 10\
173 20
174 @end example
175
176 @noindent
177 is equivalent into @samp{#define FOO 1020}.  You can split even an escape
178 sequence with Backslash-Newline.  For example, you can split @code{"foo\bar"}
179 between the @samp{\} and the @samp{b} to get
180
181 @example
182 "foo\\
183 bar"
184 @end example
185
186 @noindent
187 This behavior is unclean: in all other contexts, a Backslash can be
188 inserted in a string constant as an ordinary character by writing a double
189 Backslash, and this creates an exception.  But the ANSI C standard requires
190 it.  (Strict ANSI C does not allow Newlines in string constants, so they
191 do not consider this a problem.)
192
193 But there are a few exceptions to all three transformations.
194
195 @itemize @bullet
196 @item
197 C comments and predefined macro names are not recognized inside a
198 @samp{#include} directive in which the file name is delimited with
199 @samp{<} and @samp{>}.
200
201 @item
202 C comments and predefined macro names are never recognized within a
203 character or string constant.  (Strictly speaking, this is the rule,
204 not an exception, but it is worth noting here anyway.)
205
206 @item
207 Backslash-Newline may not safely be used within an ANSI ``trigraph''.
208 Trigraphs are converted before Backslash-Newline is deleted.  If you
209 write what looks like a trigraph with a Backslash-Newline inside, the
210 Backslash-Newline is deleted as usual, but it is then too late to
211 recognize the trigraph.
212
213 This exception is relevant only if you use the @samp{-trigraphs}
214 option to enable trigraph processing.  @xref{Invocation}.
215 @end itemize
216
217 @node Directives, Header Files, Global Actions, Top
218 @section Preprocessing Directives
219
220 @cindex preprocessing directives
221 @cindex directives
222 Most preprocessor features are active only if you use preprocessing directives
223 to request their use.
224
225 Preprocessing directives are lines in your program that start with @samp{#}.
226 The @samp{#} is followed by an identifier that is the @dfn{directive name}.
227 For example, @samp{#define} is the directive that defines a macro.
228 Whitespace is also allowed before and after the @samp{#}.
229
230 The set of valid directive names is fixed.  Programs cannot define new
231 preprocessing directives.
232
233 Some directive names require arguments; these make up the rest of the directive
234 line and must be separated from the directive name by whitespace.  For example,
235 @samp{#define} must be followed by a macro name and the intended expansion
236 of the macro.  @xref{Simple Macros}.
237
238 A preprocessing directive cannot be more than one line in normal circumstances.
239 It may be split cosmetically with Backslash-Newline, but that has no effect
240 on its meaning.  Comments containing Newlines can also divide the
241 directive into multiple lines, but the comments are changed to Spaces
242 before the directive is interpreted.  The only way a significant Newline
243 can occur in a preprocessing directive is within a string constant or
244 character constant.  Note that
245 most C compilers that might be applied to the output from the preprocessor
246 do not accept string or character constants containing Newlines.
247
248 The @samp{#} and the directive name cannot come from a macro expansion.  For
249 example, if @samp{foo} is defined as a macro expanding to @samp{define},
250 that does not make @samp{#foo} a valid preprocessing directive.
251
252 @node Header Files, Macros, Directives, Top
253 @section Header Files
254
255 @cindex header file
256 A header file is a file containing C declarations and macro definitions
257 (@pxref{Macros}) to be shared between several source files.  You request
258 the use of a header file in your program with the C preprocessing directive
259 @samp{#include}.
260
261 @menu
262 * Header Uses::         What header files are used for.
263 * Include Syntax::      How to write @samp{#include} directives.
264 * Include Operation::   What @samp{#include} does.
265 * Once-Only::           Preventing multiple inclusion of one header file.
266 * Inheritance::         Including one header file in another header file.
267 @end menu
268
269 @node Header Uses, Include Syntax, Header Files, Header Files
270 @subsection Uses of Header Files
271
272 Header files serve two kinds of purposes.
273
274 @itemize @bullet
275 @item
276 @findex system header files
277 System header files declare the interfaces to parts of the operating
278 system.  You include them in your program to supply the definitions and
279 declarations you need to invoke system calls and libraries.
280
281 @item
282 Your own header files contain declarations for interfaces between the
283 source files of your program.  Each time you have a group of related
284 declarations and macro definitions all or most of which are needed in
285 several different source files, it is a good idea to create a header
286 file for them.
287 @end itemize
288
289 Including a header file produces the same results in C compilation as
290 copying the header file into each source file that needs it.  But such
291 copying would be time-consuming and error-prone.  With a header file, the
292 related declarations appear in only one place.  If they need to be changed,
293 they can be changed in one place, and programs that include the header file
294 will automatically use the new version when next recompiled.  The header
295 file eliminates the labor of finding and changing all the copies as well as
296 the risk that a failure to find one copy will result in inconsistencies
297 within a program.
298
299 The usual convention is to give header files names that end with
300 @file{.h}.  Avoid unusual characters in header file names, as they
301 reduce portability.
302
303 @node Include Syntax, Include Operation, Header Uses, Header Files
304 @subsection The @samp{#include} Directive
305
306 @findex #include
307 Both user and system header files are included using the preprocessing
308 directive @samp{#include}.  It has three variants:
309
310 @table @code
311 @item #include <@var{file}>
312 This variant is used for system header files.  It searches for a file
313 named @var{file} in a list of directories specified by you, then in a
314 standard list of system directories.  You specify directories to
315 search for header files with the command option @samp{-I}
316 (@pxref{Invocation}).  The option @samp{-nostdinc} inhibits searching
317 the standard system directories; in this case only the directories
318 you specify are searched.
319
320 The parsing of this form of @samp{#include} is slightly special
321 because comments are not recognized within the @samp{<@dots{}>}.
322 Thus, in @samp{#include <x/*y>} the @samp{/*} does not start a comment
323 and the directive specifies inclusion of a system header file named
324 @file{x/*y}.  Of course, a header file with such a name is unlikely to
325 exist on Unix, where shell wildcard features would make it hard to
326 manipulate.@refill
327
328 The argument @var{file} may not contain a @samp{>} character.  It may,
329 however, contain a @samp{<} character.
330
331 @item #include "@var{file}"
332 This variant is used for header files of your own program.  It
333 searches for a file named @var{file} first in the current directory,
334 then in the same directories used for system header files.  The
335 current directory is the directory of the current input file.  It is
336 tried first because it is presumed to be the location of the files
337 that the current input file refers to.  (If the @samp{-I-} option is
338 used, the special treatment of the current directory is inhibited.)
339
340 The argument @var{file} may not contain @samp{"} characters.  If
341 backslashes occur within @var{file}, they are considered ordinary text
342 characters, not escape characters.  None of the character escape
343 sequences appropriate to string constants in C are processed.  Thus,
344 @samp{#include "x\n\\y"} specifies a filename containing three
345 backslashes.  It is not clear why this behavior is ever useful, but
346 the ANSI standard specifies it.
347
348 @item #include @var{anything else}
349 @cindex computed @samp{#include}
350 This variant is called a @dfn{computed #include}.  Any @samp{#include}
351 directive whose argument does not fit the above two forms is a computed
352 include.  The text @var{anything else} is checked for macro calls,
353 which are expanded (@pxref{Macros}).  When this is done, the result
354 must fit one of the above two variants---in particular, the expanded
355 text must in the end be surrounded by either quotes or angle braces.
356
357 This feature allows you to define a macro which controls the file name
358 to be used at a later point in the program.  One application of this is
359 to allow a site-specific configuration file for your program to specify
360 the names of the system include files to be used.  This can help in
361 porting the program to various operating systems in which the necessary
362 system header files are found in different places.
363 @end table
364
365 @node Include Operation, Once-Only, Include Syntax, Header Files
366 @subsection How @samp{#include} Works
367
368 The @samp{#include} directive works by directing the C preprocessor to scan
369 the specified file as input before continuing with the rest of the current
370 file.  The output from the preprocessor contains the output already
371 generated, followed by the output resulting from the included file,
372 followed by the output that comes from the text after the @samp{#include}
373 directive.  For example, given a header file @file{header.h} as follows,
374
375 @example
376 char *test ();
377 @end example
378
379 @noindent
380 and a main program called @file{program.c} that uses the header file,
381 like this,
382
383 @example
384 int x;
385 #include "header.h"
386
387 main ()
388 @{
389   printf (test ());
390 @}
391 @end example
392
393 @noindent
394 the output generated by the C preprocessor for @file{program.c} as input
395 would be
396
397 @example
398 int x;
399 char *test ();
400
401 main ()
402 @{
403   printf (test ());
404 @}
405 @end example
406
407 Included files are not limited to declarations and macro definitions; those
408 are merely the typical uses.  Any fragment of a C program can be included
409 from another file.  The include file could even contain the beginning of a
410 statement that is concluded in the containing file, or the end of a
411 statement that was started in the including file.  However, a comment or a
412 string or character constant may not start in the included file and finish
413 in the including file.  An unterminated comment, string constant or
414 character constant in an included file is considered to end (with an error
415 message) at the end of the file.
416
417 It is possible for a header file to begin or end a syntactic unit such
418 as a function definition, but that would be very confusing, so don't do
419 it.
420
421 The line following the @samp{#include} directive is always treated as a
422 separate line by the C preprocessor even if the included file lacks a final
423 newline.
424
425 @node Once-Only, Inheritance, Include Operation, Header Files
426 @subsection Once-Only Include Files
427 @cindex repeated inclusion
428 @cindex including just once
429
430 Very often, one header file includes another.  It can easily result that a
431 certain header file is included more than once.  This may lead to errors,
432 if the header file defines structure types or typedefs, and is certainly
433 wasteful.  Therefore, we often wish to prevent multiple inclusion of a
434 header file.
435
436 The standard way to do this is to enclose the entire real contents of the
437 file in a conditional, like this:
438
439 @example
440 #ifndef FILE_FOO_SEEN
441 #define FILE_FOO_SEEN
442
443 @var{the entire file}
444
445 #endif /* FILE_FOO_SEEN */
446 @end example
447
448 The macro @code{FILE_FOO_SEEN} indicates that the file has been included
449 once already.  In a user header file, the macro name should not begin
450 with @samp{_}.  In a system header file, this name should begin with
451 @samp{__} to avoid conflicts with user programs.  In any kind of header
452 file, the macro name should contain the name of the file and some
453 additional text, to avoid conflicts with other header files.
454
455 The GNU C preprocessor is programmed to notice when a header file uses
456 this particular construct and handle it efficiently.  If a header file
457 is contained entirely in a @samp{#ifndef} conditional, then it records
458 that fact.  If a subsequent @samp{#include} specifies the same file,
459 and the macro in the @samp{#ifndef} is already defined, then the file
460 is entirely skipped, without even reading it.
461
462 @findex #pragma once
463 There is also an explicit directive to tell the preprocessor that it need
464 not include a file more than once.  This is called @samp{#pragma once},
465 and was used @emph{in addition to} the @samp{#ifndef} conditional around
466 the contents of the header file.  @samp{#pragma once} is now obsolete
467 and should not be used at all.
468
469 @findex #import
470 In the Objective C language, there is a variant of @samp{#include}
471 called @samp{#import} which includes a file, but does so at most once.
472 If you use @samp{#import} @emph{instead of} @samp{#include}, then you
473 don't need the conditionals inside the header file to prevent multiple
474 execution of the contents.
475
476 @samp{#import} is obsolete because it is not a well designed feature.
477 It requires the users of a header file---the applications
478 programmers---to know that a certain header file should only be included
479 once.  It is much better for the header file's implementor to write the
480 file so that users don't need to know this.  Using @samp{#ifndef}
481 accomplishes this goal.
482
483 @node Inheritance,, Once-Only, Header Files
484 @subsection Inheritance and Header Files
485 @cindex inheritance
486 @cindex overriding a header file
487
488 @dfn{Inheritance} is what happens when one object or file derives some
489 of its contents by virtual copying from another object or file.  In
490 the case of C header files, inheritance means that one header file 
491 includes another header file and then replaces or adds something.
492
493 If the inheriting header file and the base header file have different
494 names, then inheritance is straightforward: simply write @samp{#include
495 "@var{base}"} in the inheriting file.
496
497 Sometimes it is necessary to give the inheriting file the same name as
498 the base file.  This is less straightforward.
499
500 For example, suppose an application program uses the system header
501 @file{sys/signal.h}, but the version of @file{/usr/include/sys/signal.h}
502 on a particular system doesn't do what the application program expects.
503 It might be convenient to define a ``local'' version, perhaps under the
504 name @file{/usr/local/include/sys/signal.h}, to override or add to the
505 one supplied by the system.
506
507 You can do this by compiling with the option @samp{-I.}, and
508 writing a file @file{sys/signal.h} that does what the application
509 program expects.  But making this file include the standard
510 @file{sys/signal.h} is not so easy---writing @samp{#include
511 <sys/signal.h>} in that file doesn't work, because it includes your own
512 version of the file, not the standard system version.  Used in that file
513 itself, this leads to an infinite recursion and a fatal error in
514 compilation.
515
516 @samp{#include </usr/include/sys/signal.h>} would find the proper file,
517 but that is not clean, since it makes an assumption about where the
518 system header file is found.  This is bad for maintenance, since it
519 means that any change in where the system's header files are kept
520 requires a change somewhere else.
521
522 @findex #include_next
523 The clean way to solve this problem is to use 
524 @samp{#include_next}, which means, ``Include the @emph{next} file with
525 this name.''  This directive works like @samp{#include} except in
526 searching for the specified file: it starts searching the list of header
527 file directories @emph{after} the directory in which the current file
528 was found.
529
530 Suppose you specify @samp{-I /usr/local/include}, and the list of
531 directories to search also includes @file{/usr/include}; and suppose
532 both directories contain @file{sys/signal.h}.  Ordinary
533 @samp{#include <sys/signal.h>} finds the file under
534 @file{/usr/local/include}.  If that file contains @samp{#include_next
535 <sys/signal.h>}, it starts searching after that directory, and finds the
536 file in @file{/usr/include}.
537
538 @node Macros, Conditionals, Header Files, Top
539 @section Macros
540
541 A macro is a sort of abbreviation which you can define once and then
542 use later.  There are many complicated features associated with macros
543 in the C preprocessor.
544
545 @menu
546 * Simple Macros::    Macros that always expand the same way.
547 * Argument Macros::  Macros that accept arguments that are substituted
548                        into the macro expansion.
549 * Macro Varargs::    Macros with variable number of arguments.
550 * Predefined::       Predefined macros that are always available.
551 * Stringification::  Macro arguments converted into string constants.
552 * Concatenation::    Building tokens from parts taken from macro arguments.
553 * Undefining::       Cancelling a macro's definition.
554 * Redefining::       Changing a macro's definition.
555 * Poisoning::        Ensuring a macro is never defined or used.
556 * Macro Pitfalls::   Macros can confuse the unwary.  Here we explain
557                        several common problems and strange features.
558 @end menu
559
560 @node Simple Macros, Argument Macros, Macros, Macros
561 @subsection Simple Macros
562 @cindex simple macro
563 @cindex manifest constant
564
565 A @dfn{simple macro} is a kind of abbreviation.  It is a name which
566 stands for a fragment of code.  Some people refer to these as
567 @dfn{manifest constants}.
568
569 Before you can use a macro, you must @dfn{define} it explicitly with the
570 @samp{#define} directive.  @samp{#define} is followed by the name of the
571 macro and then the code it should be an abbreviation for.  For example,
572
573 @example
574 #define BUFFER_SIZE 1020
575 @end example
576
577 @noindent
578 defines a macro named @samp{BUFFER_SIZE} as an abbreviation for the text
579 @samp{1020}.  If somewhere after this @samp{#define} directive there comes
580 a C statement of the form
581
582 @example
583 foo = (char *) xmalloc (BUFFER_SIZE);
584 @end example
585
586 @noindent
587 then the C preprocessor will recognize and @dfn{expand} the macro
588 @samp{BUFFER_SIZE}, resulting in
589
590 @example
591 foo = (char *) xmalloc (1020);
592 @end example
593
594 The use of all upper case for macro names is a standard convention.
595 Programs are easier to read when it is possible to tell at a glance which
596 names are macros.
597
598 Normally, a macro definition must be a single line, like all C
599 preprocessing directives.  (You can split a long macro definition
600 cosmetically with Backslash-Newline.)  There is one exception: Newlines
601 can be included in the macro definition if within a string or character
602 constant.  This is because it is not possible for a macro definition to
603 contain an unbalanced quote character; the definition automatically
604 extends to include the matching quote character that ends the string or
605 character constant.  Comments within a macro definition may contain
606 Newlines, which make no difference since the comments are entirely
607 replaced with Spaces regardless of their contents.
608
609 Aside from the above, there is no restriction on what can go in a macro
610 body.  Parentheses need not balance.  The body need not resemble valid C
611 code.  (But if it does not, you may get error messages from the C
612 compiler when you use the macro.)
613
614 The C preprocessor scans your program sequentially, so macro definitions
615 take effect at the place you write them.  Therefore, the following input to
616 the C preprocessor
617
618 @example
619 foo = X;
620 #define X 4
621 bar = X;
622 @end example
623
624 @noindent
625 produces as output
626
627 @example
628 foo = X;
629
630 bar = 4;
631 @end example
632
633 After the preprocessor expands a macro name, the macro's definition body is
634 appended to the front of the remaining input, and the check for macro calls
635 continues.  Therefore, the macro body can contain calls to other macros.
636 For example, after
637
638 @example
639 #define BUFSIZE 1020
640 #define TABLESIZE BUFSIZE
641 @end example
642
643 @noindent
644 the name @samp{TABLESIZE} when used in the program would go through two
645 stages of expansion, resulting ultimately in @samp{1020}.
646
647 This is not at all the same as defining @samp{TABLESIZE} to be @samp{1020}.
648 The @samp{#define} for @samp{TABLESIZE} uses exactly the body you
649 specify---in this case, @samp{BUFSIZE}---and does not check to see whether
650 it too is the name of a macro.  It's only when you @emph{use} @samp{TABLESIZE}
651 that the result of its expansion is checked for more macro names.
652 @xref{Cascaded Macros}.
653
654 @node Argument Macros, Macro Varargs, Simple Macros, Macros
655 @subsection Macros with Arguments
656 @cindex macros with argument
657 @cindex arguments in macro definitions
658 @cindex function-like macro
659
660 A simple macro always stands for exactly the same text, each time it is
661 used.  Macros can be more flexible when they accept @dfn{arguments}.
662 Arguments are fragments of code that you supply each time the macro is
663 used.  These fragments are included in the expansion of the macro
664 according to the directions in the macro definition.  A macro that
665 accepts arguments is called a @dfn{function-like macro} because the
666 syntax for using it looks like a function call.
667
668 @findex #define
669 To define a macro that uses arguments, you write a @samp{#define} directive
670 with a list of @dfn{argument names} in parentheses after the name of the
671 macro.  The argument names may be any valid C identifiers, separated by
672 commas and optionally whitespace.  The open-parenthesis must follow the
673 macro name immediately, with no space in between.
674
675 For example, here is a macro that computes the minimum of two numeric
676 values, as it is defined in many C programs:
677
678 @example
679 #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
680 @end example
681
682 @noindent
683 (This is not the best way to define a ``minimum'' macro in GNU C@.
684 @xref{Side Effects}, for more information.)
685
686 To use a macro that expects arguments, you write the name of the macro
687 followed by a list of @dfn{actual arguments} in parentheses, separated by
688 commas.  The number of actual arguments you give must match the number of
689 arguments the macro expects.   Examples of use of the macro @samp{min}
690 include @samp{min (1, 2)} and @samp{min (x + 28, *p)}.
691
692 The expansion text of the macro depends on the arguments you use.
693 Each of the argument names of the macro is replaced, throughout the
694 macro definition, with the corresponding actual argument.  Using the
695 same macro @samp{min} defined above, @samp{min (1, 2)} expands into
696
697 @example
698 ((1) < (2) ? (1) : (2))
699 @end example
700
701 @noindent
702 where @samp{1} has been substituted for @samp{X} and @samp{2} for @samp{Y}.
703
704 Likewise, @samp{min (x + 28, *p)} expands into
705
706 @example
707 ((x + 28) < (*p) ? (x + 28) : (*p))
708 @end example
709
710 Parentheses in the actual arguments must balance; a comma within
711 parentheses does not end an argument.  However, there is no requirement
712 for brackets or braces to balance, and they do not prevent a comma from
713 separating arguments.  Thus,
714
715 @example
716 macro (array[x = y, x + 1])
717 @end example
718
719 @noindent
720 passes two arguments to @code{macro}: @samp{array[x = y} and @samp{x +
721 1]}.  If you want to supply @samp{array[x = y, x + 1]} as an argument,
722 you must write it as @samp{array[(x = y, x + 1)]}, which is equivalent C
723 code.
724
725 After the actual arguments are substituted into the macro body, the entire
726 result is appended to the front of the remaining input, and the check for
727 macro calls continues.  Therefore, the actual arguments can contain calls
728 to other macros, either with or without arguments, or even to the same
729 macro.  The macro body can also contain calls to other macros.  For
730 example, @samp{min (min (a, b), c)} expands into this text:
731
732 @example
733 ((((a) < (b) ? (a) : (b))) < (c)
734  ? (((a) < (b) ? (a) : (b)))
735  : (c))
736 @end example
737
738 @noindent
739 (Line breaks shown here for clarity would not actually be generated.)
740
741 @cindex blank macro arguments
742 @cindex space as macro argument
743 If a macro @code{foo} takes one argument, and you want to supply an
744 empty argument, you must write at least some whitespace between the
745 parentheses, like this: @samp{foo ( )}.  Just @samp{foo ()} is providing
746 no arguments, which is an error if @code{foo} expects an argument.  But
747 @samp{foo0 ()} is the correct way to call a macro defined to take zero
748 arguments, like this:
749
750 @example
751 #define foo0() @dots{}
752 @end example
753
754 If you use the macro name followed by something other than an
755 open-parenthesis (after ignoring any spaces, tabs and comments that
756 follow), it is not a call to the macro, and the preprocessor does not
757 change what you have written.  Therefore, it is possible for the same name
758 to be a variable or function in your program as well as a macro, and you
759 can choose in each instance whether to refer to the macro (if an actual
760 argument list follows) or the variable or function (if an argument list
761 does not follow).
762
763 Such dual use of one name could be confusing and should be avoided
764 except when the two meanings are effectively synonymous: that is, when the
765 name is both a macro and a function and the two have similar effects.  You
766 can think of the name simply as a function; use of the name for purposes
767 other than calling it (such as, to take the address) will refer to the
768 function, while calls will expand the macro and generate better but
769 equivalent code.  For example, you can use a function named @samp{min} in
770 the same source file that defines the macro.  If you write @samp{&min} with
771 no argument list, you refer to the function.  If you write @samp{min (x,
772 bb)}, with an argument list, the macro is expanded.  If you write
773 @samp{(min) (a, bb)}, where the name @samp{min} is not followed by an
774 open-parenthesis, the macro is not expanded, so you wind up with a call to
775 the function @samp{min}.
776
777 You may not define the same name as both a simple macro and a macro with
778 arguments.
779
780 In the definition of a macro with arguments, the list of argument names
781 must follow the macro name immediately with no space in between.  If there
782 is a space after the macro name, the macro is defined as taking no
783 arguments, and all the rest of the line is taken to be the expansion.  The
784 reason for this is that it is often useful to define a macro that takes no
785 arguments and whose definition begins with an identifier in parentheses.
786 This rule about spaces makes it possible for you to do either this:
787
788 @example
789 #define FOO(x) - 1 / (x)
790 @end example
791
792 @noindent
793 (which defines @samp{FOO} to take an argument and expand into minus the
794 reciprocal of that argument) or this:
795
796 @example
797 #define BAR (x) - 1 / (x)
798 @end example
799
800 @noindent
801 (which defines @samp{BAR} to take no argument and always expand into
802 @samp{(x) - 1 / (x)}).
803
804 Note that the @emph{uses} of a macro with arguments can have spaces before
805 the left parenthesis; it's the @emph{definition} where it matters whether
806 there is a space.
807
808 @node Macro Varargs, Predefined, Argument Macros, Macros
809 @subsection Macros with Variable Numbers of Arguments
810 @cindex variable number of arguments
811 @cindex macro with variable arguments
812 @cindex rest argument (in macro)
813
814 In GNU C, a macro can accept a variable number of arguments, much as a
815 function can.  The syntax for defining the macro looks much like that
816 used for a function.  Here is an example:
817
818 @example
819 #define eprintf(format, args...)  \
820  fprintf (stderr, format , ## args)
821 @end example
822
823 Here @code{args} is a @dfn{rest argument}: it takes in zero or more
824 arguments, as many as the call contains.  All of them plus the commas
825 between them form the value of @code{args}, which is substituted into
826 the macro body where @code{args} is used.  Thus, we have this expansion:
827
828 @example
829 eprintf ("%s:%d: ", input_file_name, line_number)
830 @expansion{}
831 fprintf (stderr, "%s:%d: " , input_file_name, line_number)
832 @end example
833
834 @noindent
835 Note that the comma after the string constant comes from the definition
836 of @code{eprintf}, whereas the last comma comes from the value of
837 @code{args}.
838
839 The reason for using @samp{##} is to handle the case when @code{args}
840 matches no arguments at all.  In this case, @code{args} has an empty
841 value.  In this case, the second comma in the definition becomes an
842 embarrassment: if it got through to the expansion of the macro, we would
843 get something like this:
844
845 @example
846 fprintf (stderr, "success!\n" , )
847 @end example
848
849 @noindent
850 which is invalid C syntax.  @samp{##} gets rid of the comma, so we get
851 the following instead:
852
853 @example
854 fprintf (stderr, "success!\n")
855 @end example
856
857 This is a special feature of the GNU C preprocessor: @samp{##} before a
858 rest argument that is empty discards the preceding sequence of
859 non-whitespace characters from the macro definition.  (If another macro
860 argument precedes, none of it is discarded.)
861
862 It might be better to discard the last preprocessor token instead of the
863 last preceding sequence of non-whitespace characters; in fact, we may
864 someday change this feature to do so.  We advise you to write the macro
865 definition so that the preceding sequence of non-whitespace characters
866 is just a single token, so that the meaning will not change if we change
867 the definition of this feature.
868
869 @node Predefined, Stringification, Macro Varargs, Macros
870 @subsection Predefined Macros
871
872 @cindex predefined macros
873 Several simple macros are predefined.  You can use them without giving
874 definitions for them.  They fall into two classes: standard macros and
875 system-specific macros.
876
877 @menu
878 * Standard Predefined::     Standard predefined macros.
879 * Nonstandard Predefined::  Nonstandard predefined macros.
880 @end menu
881
882 @node Standard Predefined, Nonstandard Predefined, Predefined, Predefined
883 @subsubsection Standard Predefined Macros
884 @cindex standard predefined macros
885
886 The standard predefined macros are available with the same meanings
887 regardless of the machine or operating system on which you are using GNU C@.
888 Their names all start and end with double underscores.  Those preceding
889 @code{__GNUC__} in this table are standardized by ANSI C; the rest are
890 GNU C extensions.
891
892 @table @code
893 @item __FILE__
894 @findex __FILE__
895 This macro expands to the name of the current input file, in the form of
896 a C string constant.  The precise name returned is the one that was
897 specified in @samp{#include} or as the input file name argument.
898
899 @item __LINE__
900 @findex __LINE__
901 This macro expands to the current input line number, in the form of a
902 decimal integer constant.  While we call it a predefined macro, it's
903 a pretty strange macro, since its ``definition'' changes with each
904 new line of source code.
905
906 This and @samp{__FILE__} are useful in generating an error message to
907 report an inconsistency detected by the program; the message can state
908 the source line at which the inconsistency was detected.  For example,
909
910 @smallexample
911 fprintf (stderr, "Internal error: "
912                  "negative string length "
913                  "%d at %s, line %d.",
914          length, __FILE__, __LINE__);
915 @end smallexample
916
917 A @samp{#include} directive changes the expansions of @samp{__FILE__}
918 and @samp{__LINE__} to correspond to the included file.  At the end of
919 that file, when processing resumes on the input file that contained
920 the @samp{#include} directive, the expansions of @samp{__FILE__} and
921 @samp{__LINE__} revert to the values they had before the
922 @samp{#include} (but @samp{__LINE__} is then incremented by one as
923 processing moves to the line after the @samp{#include}).
924
925 The expansions of both @samp{__FILE__} and @samp{__LINE__} are altered
926 if a @samp{#line} directive is used.  @xref{Combining Sources}.
927
928 @item __DATE__
929 @findex __DATE__
930 This macro expands to a string constant that describes the date on
931 which the preprocessor is being run.  The string constant contains
932 eleven characters and looks like @w{@samp{"Feb  1 1996"}}.
933 @c After reformatting the above, check that the date remains `Feb  1 1996',
934 @c all on one line, with two spaces between the `Feb' and the `1'.
935
936 @item __TIME__
937 @findex __TIME__
938 This macro expands to a string constant that describes the time at
939 which the preprocessor is being run.  The string constant contains
940 eight characters and looks like @samp{"23:59:01"}.
941
942 @item __STDC__
943 @findex __STDC__
944 This macro expands to the constant 1, to signify that this is ANSI
945 Standard C@.  (Whether that is actually true depends on what C compiler
946 will operate on the output from the preprocessor.)
947
948 On some hosts, system include files use a different convention, where
949 @samp{__STDC__} is normally 0, but is 1 if the user specifies strict
950 conformance to the C Standard.  The preprocessor follows the host convention
951 when processing system include files, but when processing user files it follows
952 the usual GNU C convention.
953
954 This macro is not defined if the @samp{-traditional} option is used.
955
956 @item __STDC_VERSION__
957 @findex __STDC_VERSION__
958 This macro expands to the C Standard's version number,
959 a long integer constant of the form @samp{@var{yyyy}@var{mm}L}
960 where @var{yyyy} and @var{mm} are the year and month of the Standard version.
961 This signifies which version of the C Standard the preprocessor conforms to.
962 Like @samp{__STDC__}, whether this version number is accurate
963 for the entire implementation depends on what C compiler
964 will operate on the output from the preprocessor.
965
966 This macro is not defined if the @samp{-traditional} option is used.
967
968 @item __GNUC__
969 @findex __GNUC__
970 This macro is defined if and only if this is GNU C@.  This macro is
971 defined only when the entire GNU C compiler is in use; if you invoke the
972 preprocessor directly, @samp{__GNUC__} is undefined.  The value
973 identifies the major version number of GNU CC (@samp{1} for GNU CC
974 version 1, which is now obsolete, and @samp{2} for version 2).
975
976 @item __GNUC_MINOR__
977 @findex __GNUC_MINOR__
978 The macro contains the minor version number of the compiler.  This can
979 be used to work around differences between different releases of the
980 compiler (for example, if gcc 2.6.3 is known to support a feature, you
981 can test for @code{__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6)}).
982
983 @item __GNUC_PATCHLEVEL__
984 @findex __GNUC_PATCHLEVEL__
985 This macro contains the patch level of the compiler.  This can be
986 used to work around differences between different patch level releases
987 of the compiler (for example, if gcc 2.6.2 is known to contain a bug,
988 whereas gcc 2.6.3 contains a fix, and you have code which can workaround
989 ths problem depending on whether the bug is fixed or not, you can test for
990 @code{__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ > 6) || 
991 (__GNUC__ == 2 && __GNUC_MINOR__ == 6 && __GNUC_PATCHLEVEL__ > 3)}).
992
993 @item __GNUG__
994 @findex __GNUG__
995 The GNU C compiler defines this when the compilation language is
996 C++; use @samp{__GNUG__} to distinguish between GNU C and GNU
997 C++.
998
999 @item __cplusplus 
1000 @findex __cplusplus 
1001 The draft ANSI standard for C++ used to require predefining this
1002 variable.  Though it is no longer required, GNU C++ continues to define
1003 it, as do other popular C++ compilers.  You can use @samp{__cplusplus}
1004 to test whether a header is compiled by a C compiler or a C++ compiler.
1005
1006 @item __STRICT_ANSI__
1007 @findex __STRICT_ANSI__
1008 GNU C defines this macro if and only if the @samp{-ansi} switch was
1009 specified when GNU C was invoked.  Its definition is the null string.
1010 This macro exists primarily to direct certain GNU header files not to
1011 define certain traditional Unix constructs which are incompatible with
1012 ANSI C@.
1013
1014 @item __BASE_FILE__
1015 @findex __BASE_FILE__
1016 This macro expands to the name of the main input file, in the form
1017 of a C string constant.  This is the source file that was specified
1018 as an argument when the C compiler was invoked.
1019
1020 @item __INCLUDE_LEVEL__
1021 @findex __INCLUDE_LEVEL_
1022 This macro expands to a decimal integer constant that represents the
1023 depth of nesting in include files.  The value of this macro is
1024 incremented on every @samp{#include} directive and decremented at every
1025 end of file.  For input files specified by command line arguments,
1026 the nesting level is zero.
1027
1028 @item __VERSION__
1029 @findex __VERSION__
1030 This macro expands to a string constant which describes the version number of
1031 GNU C@.  The string is normally a sequence of decimal numbers separated
1032 by periods, such as @samp{"2.6.0"}.
1033
1034 @item __OPTIMIZE__
1035 @findex __OPTIMIZE__
1036 GNU CC defines this macro in optimizing compilations.  It causes certain
1037 GNU header files to define alternative macro definitions for some system
1038 library functions.  You should not refer to or test the definition of
1039 this macro unless you make very sure that programs will execute with the
1040 same effect regardless.
1041
1042 @item __CHAR_UNSIGNED__
1043 @findex __CHAR_UNSIGNED__
1044 GNU C defines this macro if and only if the data type @code{char} is
1045 unsigned on the target machine.  It exists to cause the standard header
1046 file @file{limits.h} to work correctly.  You should not refer to this
1047 macro yourself; instead, refer to the standard macros defined in
1048 @file{limits.h}.  The preprocessor uses this macro to determine whether
1049 or not to sign-extend large character constants written in octal; see
1050 @ref{#if Directive,,The @samp{#if} Directive}.
1051
1052 @item __REGISTER_PREFIX__
1053 @findex __REGISTER_PREFIX__
1054 This macro expands to a string (not a string constant) describing the
1055 prefix applied to CPU registers in assembler code.  You can use it to
1056 write assembler code that is usable in multiple environments.  For
1057 example, in the @samp{m68k-aout} environment it expands to the null
1058 string, but in the @samp{m68k-coff} environment it expands to the string
1059 @samp{%}.
1060
1061 @item __USER_LABEL_PREFIX__
1062 @findex __USER_LABEL_PREFIX__
1063 Similar to @code{__REGISTER_PREFIX__}, but describes the prefix applied
1064 to user generated labels in assembler code.  For example, in the
1065 @samp{m68k-aout} environment it expands to the string @samp{_}, but in
1066 the @samp{m68k-coff} environment it expands to the null string.  This
1067 does not work with the @samp{-mno-underscores} option that the i386
1068 OSF/rose and m88k targets provide nor with the @samp{-mcall*} options of
1069 the rs6000 System V Release 4 target.
1070 @end table
1071
1072 @node Nonstandard Predefined,, Standard Predefined, Predefined
1073 @subsubsection Nonstandard Predefined Macros
1074
1075 The C preprocessor normally has several predefined macros that vary between
1076 machines because their purpose is to indicate what type of system and
1077 machine is in use.  This manual, being for all systems and machines, cannot
1078 tell you exactly what their names are; instead, we offer a list of some
1079 typical ones.  You can use @samp{cpp -dM} to see the values of
1080 predefined macros; see @ref{Invocation}.
1081
1082 Some nonstandard predefined macros describe the operating system in use,
1083 with more or less specificity.  For example,
1084
1085 @table @code
1086 @item unix
1087 @findex unix
1088 @samp{unix} is normally predefined on all Unix systems.
1089
1090 @item BSD
1091 @findex BSD
1092 @samp{BSD} is predefined on recent versions of Berkeley Unix
1093 (perhaps only in version 4.3).
1094 @end table
1095
1096 Other nonstandard predefined macros describe the kind of CPU, with more or
1097 less specificity.  For example,
1098
1099 @table @code
1100 @item vax
1101 @findex vax
1102 @samp{vax} is predefined on Vax computers.
1103
1104 @item mc68000
1105 @findex mc68000
1106 @samp{mc68000} is predefined on most computers whose CPU is a Motorola
1107 68000, 68010 or 68020.
1108
1109 @item m68k
1110 @findex m68k
1111 @samp{m68k} is also predefined on most computers whose CPU is a 68000,
1112 68010 or 68020; however, some makers use @samp{mc68000} and some use
1113 @samp{m68k}.  Some predefine both names.  What happens in GNU C
1114 depends on the system you are using it on.
1115
1116 @item M68020
1117 @findex M68020
1118 @samp{M68020} has been observed to be predefined on some systems that
1119 use 68020 CPUs---in addition to @samp{mc68000} and @samp{m68k}, which
1120 are less specific.
1121
1122 @item _AM29K
1123 @findex _AM29K
1124 @itemx _AM29000
1125 @findex _AM29000
1126 Both @samp{_AM29K} and @samp{_AM29000} are predefined for the AMD 29000
1127 CPU family.
1128
1129 @item ns32000
1130 @findex ns32000
1131 @samp{ns32000} is predefined on computers which use the National
1132 Semiconductor 32000 series CPU.
1133 @end table
1134
1135 Yet other nonstandard predefined macros describe the manufacturer of
1136 the system.  For example,
1137
1138 @table @code
1139 @item sun
1140 @findex sun
1141 @samp{sun} is predefined on all models of Sun computers.
1142
1143 @item pyr
1144 @findex pyr
1145 @samp{pyr} is predefined on all models of Pyramid computers.
1146
1147 @item sequent
1148 @findex sequent
1149 @samp{sequent} is predefined on all models of Sequent computers.
1150 @end table
1151
1152 These predefined symbols are not only nonstandard, they are contrary to the
1153 ANSI standard because their names do not start with underscores.
1154 Therefore, the option @samp{-ansi} inhibits the definition of these
1155 symbols.
1156
1157 This tends to make @samp{-ansi} useless, since many programs depend on the
1158 customary nonstandard predefined symbols.  Even system header files check
1159 them and will generate incorrect declarations if they do not find the names
1160 that are expected.  You might think that the header files supplied for the
1161 Uglix computer would not need to test what machine they are running on,
1162 because they can simply assume it is the Uglix; but often they do, and they
1163 do so using the customary names.  As a result, very few C programs will
1164 compile with @samp{-ansi}.  We intend to avoid such problems on the GNU
1165 system.
1166
1167 What, then, should you do in an ANSI C program to test the type of machine
1168 it will run on?
1169
1170 GNU C offers a parallel series of symbols for this purpose, whose names
1171 are made from the customary ones by adding @samp{__} at the beginning
1172 and end.  Thus, the symbol @code{__vax__} would be available on a Vax,
1173 and so on.
1174
1175 The set of nonstandard predefined names in the GNU C preprocessor is
1176 controlled (when @code{cpp} is itself compiled) by the macro
1177 @samp{CPP_PREDEFINES}, which should be a string containing @samp{-D}
1178 options, separated by spaces.  For example, on the Sun 3, we use the
1179 following definition:
1180
1181 @example
1182 #define CPP_PREDEFINES "-Dmc68000 -Dsun -Dunix -Dm68k"
1183 @end example
1184
1185 @noindent 
1186 This macro is usually specified in @file{tm.h}.
1187
1188 @node Stringification, Concatenation, Predefined, Macros
1189 @subsection Stringification
1190
1191 @cindex stringification
1192 @dfn{Stringification} means turning a code fragment into a string constant
1193 whose contents are the text for the code fragment.  For example,
1194 stringifying @samp{foo (z)} results in @samp{"foo (z)"}.
1195
1196 In the C preprocessor, stringification is an option available when macro
1197 arguments are substituted into the macro definition.  In the body of the
1198 definition, when an argument name appears, the character @samp{#} before
1199 the name specifies stringification of the corresponding actual argument
1200 when it is substituted at that point in the definition.  The same argument
1201 may be substituted in other places in the definition without
1202 stringification if the argument name appears in those places with no
1203 @samp{#}.
1204
1205 Here is an example of a macro definition that uses stringification:
1206
1207 @smallexample
1208 @group
1209 #define WARN_IF(EXP) \
1210 do @{ if (EXP) \
1211         fprintf (stderr, "Warning: " #EXP "\n"); @} \
1212 while (0)
1213 @end group
1214 @end smallexample
1215
1216 @noindent
1217 Here the actual argument for @samp{EXP} is substituted once as given,
1218 into the @samp{if} statement, and once as stringified, into the
1219 argument to @samp{fprintf}.  The @samp{do} and @samp{while (0)} are
1220 a kludge to make it possible to write @samp{WARN_IF (@var{arg});},
1221 which the resemblance of @samp{WARN_IF} to a function would make
1222 C programmers want to do; see @ref{Swallow Semicolon}.
1223
1224 The stringification feature is limited to transforming one macro argument
1225 into one string constant: there is no way to combine the argument with
1226 other text and then stringify it all together.  But the example above shows
1227 how an equivalent result can be obtained in ANSI Standard C using the
1228 feature that adjacent string constants are concatenated as one string
1229 constant.  The preprocessor stringifies the actual value of @samp{EXP} 
1230 into a separate string constant, resulting in text like
1231
1232 @smallexample
1233 @group
1234 do @{ if (x == 0) \
1235         fprintf (stderr, "Warning: " "x == 0" "\n"); @} \
1236 while (0)
1237 @end group
1238 @end smallexample
1239
1240 @noindent
1241 but the C compiler then sees three consecutive string constants and
1242 concatenates them into one, producing effectively
1243
1244 @smallexample
1245 do @{ if (x == 0) \
1246         fprintf (stderr, "Warning: x == 0\n"); @} \
1247 while (0)
1248 @end smallexample
1249
1250 Stringification in C involves more than putting doublequote characters
1251 around the fragment; it is necessary to put backslashes in front of all
1252 doublequote characters, and all backslashes in string and character
1253 constants, in order to get a valid C string constant with the proper
1254 contents.  Thus, stringifying @samp{p = "foo\n";} results in @samp{"p =
1255 \"foo\\n\";"}.  However, backslashes that are not inside of string or
1256 character constants are not duplicated: @samp{\n} by itself stringifies to
1257 @samp{"\n"}.
1258
1259 Whitespace (including comments) in the text being stringified is handled
1260 according to precise rules.  All leading and trailing whitespace is ignored.
1261 Any sequence of whitespace in the middle of the text is converted to
1262 a single space in the stringified result.
1263
1264 @node Concatenation, Undefining, Stringification, Macros
1265 @subsection Concatenation
1266 @cindex concatenation
1267 @cindex @samp{##}
1268 @dfn{Concatenation} means joining two strings into one.  In the context
1269 of macro expansion, concatenation refers to joining two lexical units
1270 into one longer one.  Specifically, an actual argument to the macro can be
1271 concatenated with another actual argument or with fixed text to produce
1272 a longer name.  The longer name might be the name of a function,
1273 variable or type, or a C keyword; it might even be the name of another
1274 macro, in which case it will be expanded.
1275
1276 When you define a macro, you request concatenation with the special
1277 operator @samp{##} in the macro body.  When the macro is called,
1278 after actual arguments are substituted, all @samp{##} operators are
1279 deleted, and so is any whitespace next to them (including whitespace
1280 that was part of an actual argument).  The result is to concatenate
1281 the syntactic tokens on either side of the @samp{##}.
1282
1283 Consider a C program that interprets named commands.  There probably needs
1284 to be a table of commands, perhaps an array of structures declared as
1285 follows:
1286
1287 @example
1288 struct command
1289 @{
1290   char *name;
1291   void (*function) ();
1292 @};
1293
1294 struct command commands[] =
1295 @{
1296   @{ "quit", quit_command@},
1297   @{ "help", help_command@},
1298   @dots{}
1299 @};
1300 @end example
1301
1302 It would be cleaner not to have to give each command name twice, once in
1303 the string constant and once in the function name.  A macro which takes the
1304 name of a command as an argument can make this unnecessary.  The string
1305 constant can be created with stringification, and the function name by
1306 concatenating the argument with @samp{_command}.  Here is how it is done:
1307
1308 @example
1309 #define COMMAND(NAME)  @{ #NAME, NAME ## _command @}
1310
1311 struct command commands[] =
1312 @{
1313   COMMAND (quit),
1314   COMMAND (help),
1315   @dots{}
1316 @};
1317 @end example
1318
1319 The usual case of concatenation is concatenating two names (or a name and a
1320 number) into a longer name.  But this isn't the only valid case.  It is
1321 also possible to concatenate two numbers (or a number and a name, such as
1322 @samp{1.5} and @samp{e3}) into a number.  Also, multi-character operators
1323 such as @samp{+=} can be formed by concatenation.  In some cases it is even
1324 possible to piece together a string constant.  However, two pieces of text
1325 that don't together form a valid lexical unit cannot be concatenated.  For
1326 example, concatenation with @samp{x} on one side and @samp{+} on the other
1327 is not meaningful because those two characters can't fit together in any
1328 lexical unit of C@.  The ANSI standard says that such attempts at
1329 concatenation are undefined, but in the GNU C preprocessor it is well
1330 defined: it puts the @samp{x} and @samp{+} side by side with no particular
1331 special results.
1332
1333 Keep in mind that the C preprocessor converts comments to whitespace before
1334 macros are even considered.  Therefore, you cannot create a comment by
1335 concatenating @samp{/} and @samp{*}: the @samp{/*} sequence that starts a
1336 comment is not a lexical unit, but rather the beginning of a ``long'' space
1337 character.  Also, you can freely use comments next to a @samp{##} in a
1338 macro definition, or in actual arguments that will be concatenated, because
1339 the comments will be converted to spaces at first sight, and concatenation
1340 will later discard the spaces.
1341
1342 @node Undefining, Redefining, Concatenation, Macros
1343 @subsection Undefining Macros
1344
1345 @cindex undefining macros
1346 To @dfn{undefine} a macro means to cancel its definition.  This is done
1347 with the @samp{#undef} directive.  @samp{#undef} is followed by the macro
1348 name to be undefined.
1349
1350 Like definition, undefinition occurs at a specific point in the source
1351 file, and it applies starting from that point.  The name ceases to be a
1352 macro name, and from that point on it is treated by the preprocessor as if
1353 it had never been a macro name.
1354
1355 For example,
1356
1357 @example
1358 #define FOO 4
1359 x = FOO;
1360 #undef FOO
1361 x = FOO;
1362 @end example
1363
1364 @noindent
1365 expands into
1366
1367 @example
1368 x = 4;
1369
1370 x = FOO;
1371 @end example
1372
1373 @noindent
1374 In this example, @samp{FOO} had better be a variable or function as well
1375 as (temporarily) a macro, in order for the result of the expansion to be
1376 valid C code.
1377
1378 The same form of @samp{#undef} directive will cancel definitions with
1379 arguments or definitions that don't expect arguments.  The @samp{#undef}
1380 directive has no effect when used on a name not currently defined as a macro.
1381
1382 @node Redefining, Poisoning, Undefining, Macros
1383 @subsection Redefining Macros
1384
1385 @cindex redefining macros
1386 @dfn{Redefining} a macro means defining (with @samp{#define}) a name that
1387 is already defined as a macro.
1388
1389 A redefinition is trivial if the new definition is transparently identical
1390 to the old one.  You probably wouldn't deliberately write a trivial
1391 redefinition, but they can happen automatically when a header file is
1392 included more than once (@pxref{Header Files}), so they are accepted
1393 silently and without effect.
1394
1395 Nontrivial redefinition is considered likely to be an error, so
1396 it provokes a warning message from the preprocessor.  However, sometimes it
1397 is useful to change the definition of a macro in mid-compilation.  You can
1398 inhibit the warning by undefining the macro with @samp{#undef} before the
1399 second definition.
1400
1401 In order for a redefinition to be trivial, the new definition must
1402 exactly match the one already in effect, with two possible exceptions:
1403
1404 @itemize @bullet
1405 @item
1406 Whitespace may be added or deleted at the beginning or the end.
1407
1408 @item
1409 Whitespace may be changed in the middle (but not inside strings).
1410 However, it may not be eliminated entirely, and it may not be added
1411 where there was no whitespace at all.
1412 @end itemize
1413
1414 Recall that a comment counts as whitespace.
1415
1416 @node Poisoning, Macro Pitfalls, Redefining, Macros
1417 @subsection Poisoning Macros
1418 @cindex poisoning macros
1419
1420 Sometimes, there is an identifier that you want to remove completely
1421 from your program, and make sure that it never creeps back in.  To
1422 enforce this, the @samp{#pragma poison} directive can be used.
1423 @samp{#pragma poison} is followed by a list of identifiers to poison,
1424 and takes effect for the rest of the source.  You cannot @samp{#undef} a
1425 poisoned identifier or test to see if it's defined with @samp{#ifdef}.
1426
1427 For example,
1428
1429 @example
1430 #pragma poison printf sprintf fprintf
1431 sprintf(some_string, "hello");
1432 @end example
1433
1434 @noindent
1435 will produce an error.
1436
1437 @node Macro Pitfalls,, Poisoning, Macros
1438 @subsection Pitfalls and Subtleties of Macros
1439 @cindex problems with macros
1440 @cindex pitfalls of macros
1441
1442 In this section we describe some special rules that apply to macros and
1443 macro expansion, and point out certain cases in which the rules have
1444 counterintuitive consequences that you must watch out for.
1445
1446 @menu
1447 * Misnesting::        Macros can contain unmatched parentheses.
1448 * Macro Parentheses:: Why apparently superfluous parentheses
1449                          may be necessary to avoid incorrect grouping.
1450 * Swallow Semicolon:: Macros that look like functions
1451                          but expand into compound statements.
1452 * Side Effects::      Unsafe macros that cause trouble when
1453                          arguments contain side effects.
1454 * Self-Reference::    Macros whose definitions use the macros' own names.
1455 * Argument Prescan::  Actual arguments are checked for macro calls
1456                          before they are substituted.
1457 * Cascaded Macros::   Macros whose definitions use other macros.
1458 * Newlines in Args::  Sometimes line numbers get confused.
1459 @end menu
1460
1461 @node Misnesting, Macro Parentheses, Macro Pitfalls, Macro Pitfalls
1462 @subsubsection Improperly Nested Constructs
1463
1464 Recall that when a macro is called with arguments, the arguments are
1465 substituted into the macro body and the result is checked, together with
1466 the rest of the input file, for more macro calls.
1467
1468 It is possible to piece together a macro call coming partially from the
1469 macro body and partially from the actual arguments.  For example,
1470
1471 @example
1472 #define double(x) (2*(x))
1473 #define call_with_1(x) x(1)
1474 @end example
1475
1476 @noindent
1477 would expand @samp{call_with_1 (double)} into @samp{(2*(1))}.
1478
1479 Macro definitions do not have to have balanced parentheses.  By writing an
1480 unbalanced open parenthesis in a macro body, it is possible to create a
1481 macro call that begins inside the macro body but ends outside of it.  For
1482 example,
1483
1484 @example
1485 #define strange(file) fprintf (file, "%s %d",
1486 @dots{}
1487 strange(stderr) p, 35)
1488 @end example
1489
1490 @noindent
1491 This bizarre example expands to @samp{fprintf (stderr, "%s %d", p, 35)}!
1492
1493 @node Macro Parentheses, Swallow Semicolon, Misnesting, Macro Pitfalls
1494 @subsubsection Unintended Grouping of Arithmetic
1495 @cindex parentheses in macro bodies
1496
1497 You may have noticed that in most of the macro definition examples shown
1498 above, each occurrence of a macro argument name had parentheses around it.
1499 In addition, another pair of parentheses usually surround the entire macro
1500 definition.  Here is why it is best to write macros that way.
1501
1502 Suppose you define a macro as follows,
1503
1504 @example
1505 #define ceil_div(x, y) (x + y - 1) / y
1506 @end example
1507
1508 @noindent
1509 whose purpose is to divide, rounding up.  (One use for this operation is
1510 to compute how many @samp{int} objects are needed to hold a certain
1511 number of @samp{char} objects.)  Then suppose it is used as follows:
1512
1513 @example
1514 a = ceil_div (b & c, sizeof (int));
1515 @end example
1516
1517 @noindent
1518 This expands into
1519
1520 @example
1521 a = (b & c + sizeof (int) - 1) / sizeof (int);
1522 @end example
1523
1524 @noindent
1525 which does not do what is intended.  The operator-precedence rules of
1526 C make it equivalent to this:
1527
1528 @example
1529 a = (b & (c + sizeof (int) - 1)) / sizeof (int);
1530 @end example
1531
1532 @noindent
1533 But what we want is this:
1534
1535 @example
1536 a = ((b & c) + sizeof (int) - 1)) / sizeof (int);
1537 @end example
1538
1539 @noindent
1540 Defining the macro as
1541
1542 @example
1543 #define ceil_div(x, y) ((x) + (y) - 1) / (y)
1544 @end example
1545
1546 @noindent
1547 provides the desired result.
1548
1549 Unintended grouping can result in another way.  Consider
1550 @samp{sizeof ceil_div(1, 2)}.  That has the appearance of a C expression
1551 that would compute the size of the type of @samp{ceil_div (1, 2)}, but in
1552 fact it means something very different.  Here is what it expands to:
1553
1554 @example
1555 sizeof ((1) + (2) - 1) / (2)
1556 @end example
1557
1558 @noindent
1559 This would take the size of an integer and divide it by two.  The precedence
1560 rules have put the division outside the @samp{sizeof} when it was intended
1561 to be inside.
1562
1563 Parentheses around the entire macro definition can prevent such problems.
1564 Here, then, is the recommended way to define @samp{ceil_div}:
1565
1566 @example
1567 #define ceil_div(x, y) (((x) + (y) - 1) / (y))
1568 @end example
1569
1570 @node Swallow Semicolon, Side Effects, Macro Parentheses, Macro Pitfalls
1571 @subsubsection Swallowing the Semicolon
1572
1573 @cindex semicolons (after macro calls)
1574 Often it is desirable to define a macro that expands into a compound
1575 statement.  Consider, for example, the following macro, that advances a
1576 pointer (the argument @samp{p} says where to find it) across whitespace
1577 characters:
1578
1579 @example
1580 #define SKIP_SPACES(p, limit)  \
1581 @{ register char *lim = (limit); \
1582   while (p != lim) @{            \
1583     if (*p++ != ' ') @{          \
1584       p--; break; @}@}@}
1585 @end example
1586
1587 @noindent
1588 Here Backslash-Newline is used to split the macro definition, which must
1589 be a single line, so that it resembles the way such C code would be
1590 laid out if not part of a macro definition.
1591
1592 A call to this macro might be @samp{SKIP_SPACES (p, lim)}.  Strictly
1593 speaking, the call expands to a compound statement, which is a complete
1594 statement with no need for a semicolon to end it.  But it looks like a
1595 function call.  So it minimizes confusion if you can use it like a function
1596 call, writing a semicolon afterward, as in @samp{SKIP_SPACES (p, lim);}
1597
1598 But this can cause trouble before @samp{else} statements, because the
1599 semicolon is actually a null statement.  Suppose you write
1600
1601 @example
1602 if (*p != 0)
1603   SKIP_SPACES (p, lim);
1604 else @dots{}
1605 @end example
1606
1607 @noindent
1608 The presence of two statements---the compound statement and a null
1609 statement---in between the @samp{if} condition and the @samp{else}
1610 makes invalid C code.
1611
1612 The definition of the macro @samp{SKIP_SPACES} can be altered to solve
1613 this problem, using a @samp{do @dots{} while} statement.  Here is how:
1614
1615 @example
1616 #define SKIP_SPACES(p, limit)     \
1617 do @{ register char *lim = (limit); \
1618      while (p != lim) @{            \
1619        if (*p++ != ' ') @{          \
1620          p--; break; @}@}@}           \
1621 while (0)
1622 @end example
1623
1624 Now @samp{SKIP_SPACES (p, lim);} expands into
1625
1626 @example
1627 do @{@dots{}@} while (0);
1628 @end example
1629
1630 @noindent
1631 which is one statement.
1632
1633 @node Side Effects, Self-Reference, Swallow Semicolon, Macro Pitfalls
1634 @subsubsection Duplication of Side Effects
1635
1636 @cindex side effects (in macro arguments)
1637 @cindex unsafe macros
1638 Many C programs define a macro @samp{min}, for ``minimum'', like this:
1639
1640 @example
1641 #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
1642 @end example
1643
1644 When you use this macro with an argument containing a side effect,
1645 as shown here,
1646
1647 @example
1648 next = min (x + y, foo (z));
1649 @end example
1650
1651 @noindent
1652 it expands as follows:
1653
1654 @example
1655 next = ((x + y) < (foo (z)) ? (x + y) : (foo (z)));
1656 @end example
1657
1658 @noindent
1659 where @samp{x + y} has been substituted for @samp{X} and @samp{foo (z)}
1660 for @samp{Y}.
1661
1662 The function @samp{foo} is used only once in the statement as it appears
1663 in the program, but the expression @samp{foo (z)} has been substituted
1664 twice into the macro expansion.  As a result, @samp{foo} might be called
1665 two times when the statement is executed.  If it has side effects or
1666 if it takes a long time to compute, the results might not be what you
1667 intended.  We say that @samp{min} is an @dfn{unsafe} macro.
1668
1669 The best solution to this problem is to define @samp{min} in a way that
1670 computes the value of @samp{foo (z)} only once.  The C language offers no
1671 standard way to do this, but it can be done with GNU C extensions as
1672 follows:
1673
1674 @example
1675 #define min(X, Y)                     \
1676 (@{ typeof (X) __x = (X), __y = (Y);   \
1677    (__x < __y) ? __x : __y; @})
1678 @end example
1679
1680 If you do not wish to use GNU C extensions, the only solution is to be
1681 careful when @emph{using} the macro @samp{min}.  For example, you can
1682 calculate the value of @samp{foo (z)}, save it in a variable, and use that
1683 variable in @samp{min}:
1684
1685 @example
1686 #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
1687 @dots{}
1688 @{
1689   int tem = foo (z);
1690   next = min (x + y, tem);
1691 @}
1692 @end example
1693
1694 @noindent
1695 (where we assume that @samp{foo} returns type @samp{int}).
1696
1697 @node Self-Reference, Argument Prescan, Side Effects, Macro Pitfalls
1698 @subsubsection Self-Referential Macros
1699
1700 @cindex self-reference
1701 A @dfn{self-referential} macro is one whose name appears in its definition.
1702 A special feature of ANSI Standard C is that the self-reference is not
1703 considered a macro call.  It is passed into the preprocessor output
1704 unchanged.
1705
1706 Let's consider an example:
1707
1708 @example
1709 #define foo (4 + foo)
1710 @end example
1711
1712 @noindent
1713 where @samp{foo} is also a variable in your program.
1714
1715 Following the ordinary rules, each reference to @samp{foo} will expand into
1716 @samp{(4 + foo)}; then this will be rescanned and will expand into @samp{(4
1717 + (4 + foo))}; and so on until it causes a fatal error (memory full) in the
1718 preprocessor.
1719
1720 However, the special rule about self-reference cuts this process short
1721 after one step, at @samp{(4 + foo)}.  Therefore, this macro definition
1722 has the possibly useful effect of causing the program to add 4 to
1723 the value of @samp{foo} wherever @samp{foo} is referred to.
1724
1725 In most cases, it is a bad idea to take advantage of this feature.  A
1726 person reading the program who sees that @samp{foo} is a variable will
1727 not expect that it is a macro as well.  The reader will come across the
1728 identifier @samp{foo} in the program and think its value should be that
1729 of the variable @samp{foo}, whereas in fact the value is four greater.
1730
1731 The special rule for self-reference applies also to @dfn{indirect}
1732 self-reference.  This is the case where a macro @var{x} expands to use a
1733 macro @samp{y}, and the expansion of @samp{y} refers to the macro
1734 @samp{x}.  The resulting reference to @samp{x} comes indirectly from the
1735 expansion of @samp{x}, so it is a self-reference and is not further
1736 expanded.  Thus, after
1737
1738 @example
1739 #define x (4 + y)
1740 #define y (2 * x)
1741 @end example
1742
1743 @noindent
1744 @samp{x} would expand into @samp{(4 + (2 * x))}.  Clear?
1745
1746 But suppose @samp{y} is used elsewhere, not from the definition of @samp{x}.
1747 Then the use of @samp{x} in the expansion of @samp{y} is not a self-reference
1748 because @samp{x} is not ``in progress''.  So it does expand.  However,
1749 the expansion of @samp{x} contains a reference to @samp{y}, and that
1750 is an indirect self-reference now because @samp{y} is ``in progress''.
1751 The result is that @samp{y} expands to @samp{(2 * (4 + y))}.
1752
1753 It is not clear that this behavior would ever be useful, but it is specified
1754 by the ANSI C standard, so you may need to understand it.
1755
1756 @node Argument Prescan, Cascaded Macros, Self-Reference, Macro Pitfalls
1757 @subsubsection Separate Expansion of Macro Arguments
1758 @cindex expansion of arguments
1759 @cindex macro argument expansion
1760 @cindex prescan of macro arguments
1761
1762 We have explained that the expansion of a macro, including the substituted
1763 actual arguments, is scanned over again for macro calls to be expanded.
1764
1765 What really happens is more subtle: first each actual argument text is scanned
1766 separately for macro calls.  Then the results of this are substituted into
1767 the macro body to produce the macro expansion, and the macro expansion
1768 is scanned again for macros to expand.
1769
1770 The result is that the actual arguments are scanned @emph{twice} to expand
1771 macro calls in them.
1772
1773 Most of the time, this has no effect.  If the actual argument contained
1774 any macro calls, they are expanded during the first scan.  The result
1775 therefore contains no macro calls, so the second scan does not change it.
1776 If the actual argument were substituted as given, with no prescan,
1777 the single remaining scan would find the same macro calls and produce
1778 the same results.
1779
1780 You might expect the double scan to change the results when a
1781 self-referential macro is used in an actual argument of another macro
1782 (@pxref{Self-Reference}): the self-referential macro would be expanded once
1783 in the first scan, and a second time in the second scan.  But this is not
1784 what happens.  The self-references that do not expand in the first scan are
1785 marked so that they will not expand in the second scan either.
1786
1787 The prescan is not done when an argument is stringified or concatenated.
1788 Thus,
1789
1790 @example
1791 #define str(s) #s
1792 #define foo 4
1793 str (foo)
1794 @end example
1795
1796 @noindent
1797 expands to @samp{"foo"}.  Once more, prescan has been prevented from
1798 having any noticeable effect.
1799
1800 More precisely, stringification and concatenation use the argument as
1801 written, in un-prescanned form.  The same actual argument would be used in
1802 prescanned form if it is substituted elsewhere without stringification or
1803 concatenation.
1804
1805 @example
1806 #define str(s) #s lose(s)
1807 #define foo 4
1808 str (foo)
1809 @end example
1810
1811 expands to @samp{"foo" lose(4)}.
1812
1813 You might now ask, ``Why mention the prescan, if it makes no difference?
1814 And why not skip it and make the preprocessor faster?''  The answer is
1815 that the prescan does make a difference in three special cases:
1816
1817 @itemize @bullet
1818 @item
1819 Nested calls to a macro.
1820
1821 @item
1822 Macros that call other macros that stringify or concatenate.
1823
1824 @item
1825 Macros whose expansions contain unshielded commas.
1826 @end itemize
1827
1828 We say that @dfn{nested} calls to a macro occur when a macro's actual
1829 argument contains a call to that very macro.  For example, if @samp{f}
1830 is a macro that expects one argument, @samp{f (f (1))} is a nested
1831 pair of calls to @samp{f}.  The desired expansion is made by
1832 expanding @samp{f (1)} and substituting that into the definition of
1833 @samp{f}.  The prescan causes the expected result to happen.
1834 Without the prescan, @samp{f (1)} itself would be substituted as
1835 an actual argument, and the inner use of @samp{f} would appear
1836 during the main scan as an indirect self-reference and would not
1837 be expanded.  Here, the prescan cancels an undesirable side effect
1838 (in the medical, not computational, sense of the term) of the special
1839 rule for self-referential macros.
1840
1841 But prescan causes trouble in certain other cases of nested macro calls.
1842 Here is an example:
1843
1844 @example
1845 #define foo  a,b
1846 #define bar(x) lose(x)
1847 #define lose(x) (1 + (x))
1848
1849 bar(foo)
1850 @end example
1851
1852 @noindent
1853 We would like @samp{bar(foo)} to turn into @samp{(1 + (foo))}, which
1854 would then turn into @samp{(1 + (a,b))}.  But instead, @samp{bar(foo)}
1855 expands into @samp{lose(a,b)}, and you get an error because @code{lose}
1856 requires a single argument.  In this case, the problem is easily solved
1857 by the same parentheses that ought to be used to prevent misnesting of
1858 arithmetic operations:
1859
1860 @example
1861 #define foo (a,b)
1862 #define bar(x) lose((x))
1863 @end example
1864
1865 The problem is more serious when the operands of the macro are not
1866 expressions; for example, when they are statements.  Then parentheses
1867 are unacceptable because they would make for invalid C code:
1868
1869 @example
1870 #define foo @{ int a, b; @dots{} @}
1871 @end example
1872
1873 @noindent
1874 In GNU C you can shield the commas using the @samp{(@{@dots{}@})}
1875 construct which turns a compound statement into an expression:
1876
1877 @example
1878 #define foo (@{ int a, b; @dots{} @})
1879 @end example
1880
1881 Or you can rewrite the macro definition to avoid such commas:
1882
1883 @example
1884 #define foo @{ int a; int b; @dots{} @}
1885 @end example
1886
1887 There is also one case where prescan is useful.  It is possible
1888 to use prescan to expand an argument and then stringify it---if you use
1889 two levels of macros.  Let's add a new macro @samp{xstr} to the
1890 example shown above:
1891
1892 @example
1893 #define xstr(s) str(s)
1894 #define str(s) #s
1895 #define foo 4
1896 xstr (foo)
1897 @end example
1898
1899 This expands into @samp{"4"}, not @samp{"foo"}.  The reason for the
1900 difference is that the argument of @samp{xstr} is expanded at prescan
1901 (because @samp{xstr} does not specify stringification or concatenation of
1902 the argument).  The result of prescan then forms the actual argument for
1903 @samp{str}.  @samp{str} uses its argument without prescan because it
1904 performs stringification; but it cannot prevent or undo the prescanning
1905 already done by @samp{xstr}.
1906
1907 @node Cascaded Macros, Newlines in Args, Argument Prescan, Macro Pitfalls
1908 @subsubsection Cascaded Use of Macros
1909
1910 @cindex cascaded macros
1911 @cindex macro body uses macro
1912 A @dfn{cascade} of macros is when one macro's body contains a reference
1913 to another macro.  This is very common practice.  For example,
1914
1915 @example
1916 #define BUFSIZE 1020
1917 #define TABLESIZE BUFSIZE
1918 @end example
1919
1920 This is not at all the same as defining @samp{TABLESIZE} to be @samp{1020}.
1921 The @samp{#define} for @samp{TABLESIZE} uses exactly the body you
1922 specify---in this case, @samp{BUFSIZE}---and does not check to see whether
1923 it too is the name of a macro.
1924
1925 It's only when you @emph{use} @samp{TABLESIZE} that the result of its expansion
1926 is checked for more macro names.
1927
1928 This makes a difference if you change the definition of @samp{BUFSIZE}
1929 at some point in the source file.  @samp{TABLESIZE}, defined as shown,
1930 will always expand using the definition of @samp{BUFSIZE} that is
1931 currently in effect:
1932
1933 @example
1934 #define BUFSIZE 1020
1935 #define TABLESIZE BUFSIZE
1936 #undef BUFSIZE
1937 #define BUFSIZE 37
1938 @end example
1939
1940 @noindent
1941 Now @samp{TABLESIZE} expands (in two stages) to @samp{37}.  (The
1942 @samp{#undef} is to prevent any warning about the nontrivial
1943 redefinition of @code{BUFSIZE}.)
1944
1945 @node Newlines in Args,, Cascaded Macros, Macro Pitfalls
1946 @subsection Newlines in Macro Arguments
1947 @cindex newlines in macro arguments
1948
1949 Traditional macro processing carries forward all newlines in macro
1950 arguments into the expansion of the macro.  This means that, if some of
1951 the arguments are substituted more than once, or not at all, or out of
1952 order, newlines can be duplicated, lost, or moved around within the
1953 expansion.  If the expansion consists of multiple statements, then the
1954 effect is to distort the line numbers of some of these statements.  The
1955 result can be incorrect line numbers, in error messages or displayed in
1956 a debugger.
1957
1958 The GNU C preprocessor operating in ANSI C mode adjusts appropriately
1959 for multiple use of an argument---the first use expands all the
1960 newlines, and subsequent uses of the same argument produce no newlines.
1961 But even in this mode, it can produce incorrect line numbering if
1962 arguments are used out of order, or not used at all.
1963
1964 Here is an example illustrating this problem:
1965
1966 @example
1967 #define ignore_second_arg(a,b,c) a; c
1968
1969 ignore_second_arg (foo (),
1970                    ignored (),
1971                    syntax error);
1972 @end example
1973
1974 @noindent
1975 The syntax error triggered by the tokens @samp{syntax error} results
1976 in an error message citing line four, even though the statement text
1977 comes from line five.
1978
1979 @node Conditionals, Combining Sources, Macros, Top
1980 @section Conditionals
1981
1982 @cindex conditionals
1983 In a macro processor, a @dfn{conditional} is a directive that allows a part
1984 of the program to be ignored during compilation, on some conditions.
1985 In the C preprocessor, a conditional can test either an arithmetic expression
1986 or whether a name is defined as a macro.
1987
1988 A conditional in the C preprocessor resembles in some ways an @samp{if}
1989 statement in C, but it is important to understand the difference between
1990 them.  The condition in an @samp{if} statement is tested during the execution
1991 of your program.  Its purpose is to allow your program to behave differently
1992 from run to run, depending on the data it is operating on.  The condition
1993 in a preprocessing conditional directive is tested when your program is compiled.
1994 Its purpose is to allow different code to be included in the program depending
1995 on the situation at the time of compilation.
1996
1997 @menu
1998 * Uses: Conditional Uses.       What conditionals are for.
1999 * Syntax: Conditional Syntax.   How conditionals are written.
2000 * Deletion: Deleted Code.       Making code into a comment.
2001 * Macros: Conditionals-Macros.  Why conditionals are used with macros.
2002 * Assertions::                  How and why to use assertions.
2003 * Errors: #error Directive.     Detecting inconsistent compilation parameters.
2004 @end menu
2005
2006 @node Conditional Uses
2007 @subsection Why Conditionals are Used
2008
2009 Generally there are three kinds of reason to use a conditional.
2010
2011 @itemize @bullet
2012 @item
2013 A program may need to use different code depending on the machine or
2014 operating system it is to run on.  In some cases the code for one
2015 operating system may be erroneous on another operating system; for
2016 example, it might refer to library routines that do not exist on the
2017 other system.  When this happens, it is not enough to avoid executing
2018 the invalid code: merely having it in the program makes it impossible
2019 to link the program and run it.  With a preprocessing conditional, the
2020 offending code can be effectively excised from the program when it is
2021 not valid.
2022
2023 @item
2024 You may want to be able to compile the same source file into two
2025 different programs.  Sometimes the difference between the programs is
2026 that one makes frequent time-consuming consistency checks on its
2027 intermediate data, or prints the values of those data for debugging,
2028 while the other does not.
2029
2030 @item
2031 A conditional whose condition is always false is a good way to exclude
2032 code from the program but keep it as a sort of comment for future
2033 reference.
2034 @end itemize
2035
2036 Most simple programs that are intended to run on only one machine will
2037 not need to use preprocessing conditionals.
2038
2039 @node Conditional Syntax
2040 @subsection Syntax of Conditionals
2041
2042 @findex #if
2043 A conditional in the C preprocessor begins with a @dfn{conditional
2044 directive}: @samp{#if}, @samp{#ifdef} or @samp{#ifndef}.
2045 @xref{Conditionals-Macros}, for information on @samp{#ifdef} and
2046 @samp{#ifndef}; only @samp{#if} is explained here.
2047
2048 @menu
2049 * If: #if Directive.     Basic conditionals using @samp{#if} and @samp{#endif}.
2050 * Else: #else Directive. Including some text if the condition fails.
2051 * Elif: #elif Directive. Testing several alternative possibilities.
2052 @end menu
2053
2054 @node #if Directive
2055 @subsubsection The @samp{#if} Directive
2056
2057 The @samp{#if} directive in its simplest form consists of
2058
2059 @example
2060 #if @var{expression}
2061 @var{controlled text}
2062 #endif /* @var{expression} */
2063 @end example
2064
2065 The comment following the @samp{#endif} is not required, but it is a good
2066 practice because it helps people match the @samp{#endif} to the
2067 corresponding @samp{#if}.  Such comments should always be used, except in
2068 short conditionals that are not nested.  In fact, you can put anything at
2069 all after the @samp{#endif} and it will be ignored by the GNU C preprocessor,
2070 but only comments are acceptable in ANSI Standard C@.
2071
2072 @var{expression} is a C expression of integer type, subject to stringent
2073 restrictions.  It may contain
2074
2075 @itemize @bullet
2076 @item
2077 Integer constants, which are all regarded as @code{long} or
2078 @code{unsigned long}.
2079
2080 @item
2081 Character constants, which are interpreted according to the character
2082 set and conventions of the machine and operating system on which the
2083 preprocessor is running.  The GNU C preprocessor uses the C data type
2084 @samp{char} for these character constants; therefore, whether some
2085 character codes are negative is determined by the C compiler used to
2086 compile the preprocessor.  If it treats @samp{char} as signed, then
2087 character codes large enough to set the sign bit will be considered
2088 negative; otherwise, no character code is considered negative.
2089
2090 @item
2091 Arithmetic operators for addition, subtraction, multiplication,
2092 division, bitwise operations, shifts, comparisons, and logical
2093 operations (@samp{&&} and @samp{||}).
2094
2095 @item
2096 Identifiers that are not macros, which are all treated as zero(!).
2097
2098 @item
2099 Macro calls.  All macro calls in the expression are expanded before
2100 actual computation of the expression's value begins.
2101 @end itemize
2102
2103 Note that @samp{sizeof} operators and @code{enum}-type values are not allowed.
2104 @code{enum}-type values, like all other identifiers that are not taken
2105 as macro calls and expanded, are treated as zero.
2106
2107 The @var{controlled text} inside of a conditional can include
2108 preprocessing directives.  Then the directives inside the conditional are
2109 obeyed only if that branch of the conditional succeeds.  The text can
2110 also contain other conditional groups.  However, the @samp{#if} and
2111 @samp{#endif} directives must balance.
2112
2113 @node #else Directive
2114 @subsubsection The @samp{#else} Directive
2115
2116 @findex #else
2117 The @samp{#else} directive can be added to a conditional to provide
2118 alternative text to be used if the condition is false.  This is what
2119 it looks like:
2120
2121 @example
2122 #if @var{expression}
2123 @var{text-if-true}
2124 #else /* Not @var{expression} */
2125 @var{text-if-false}
2126 #endif /* Not @var{expression} */
2127 @end example
2128
2129 If @var{expression} is nonzero, and thus the @var{text-if-true} is 
2130 active, then @samp{#else} acts like a failing conditional and the
2131 @var{text-if-false} is ignored.  Contrariwise, if the @samp{#if}
2132 conditional fails, the @var{text-if-false} is considered included.
2133
2134 @node #elif Directive
2135 @subsubsection The @samp{#elif} Directive
2136
2137 @findex #elif
2138 One common case of nested conditionals is used to check for more than two
2139 possible alternatives.  For example, you might have
2140
2141 @example
2142 #if X == 1
2143 @dots{}
2144 #else /* X != 1 */
2145 #if X == 2
2146 @dots{}
2147 #else /* X != 2 */
2148 @dots{}
2149 #endif /* X != 2 */
2150 #endif /* X != 1 */
2151 @end example
2152
2153 Another conditional directive, @samp{#elif}, allows this to be abbreviated
2154 as follows:
2155
2156 @example
2157 #if X == 1
2158 @dots{}
2159 #elif X == 2
2160 @dots{}
2161 #else /* X != 2 and X != 1*/
2162 @dots{}
2163 #endif /* X != 2 and X != 1*/
2164 @end example
2165
2166 @samp{#elif} stands for ``else if''.  Like @samp{#else}, it goes in the
2167 middle of a @samp{#if}-@samp{#endif} pair and subdivides it; it does not
2168 require a matching @samp{#endif} of its own.  Like @samp{#if}, the
2169 @samp{#elif} directive includes an expression to be tested.
2170
2171 The text following the @samp{#elif} is processed only if the original
2172 @samp{#if}-condition failed and the @samp{#elif} condition succeeds.
2173 More than one @samp{#elif} can go in the same @samp{#if}-@samp{#endif}
2174 group.  Then the text after each @samp{#elif} is processed only if the
2175 @samp{#elif} condition succeeds after the original @samp{#if} and any
2176 previous @samp{#elif} directives within it have failed.  @samp{#else} is
2177 equivalent to @samp{#elif 1}, and @samp{#else} is allowed after any
2178 number of @samp{#elif} directives, but @samp{#elif} may not follow
2179 @samp{#else}.
2180
2181 @node Deleted Code
2182 @subsection Keeping Deleted Code for Future Reference
2183 @cindex commenting out code
2184
2185 If you replace or delete a part of the program but want to keep the old
2186 code around as a comment for future reference, the easy way to do this
2187 is to put @samp{#if 0} before it and @samp{#endif} after it.  This is
2188 better than using comment delimiters @samp{/*} and @samp{*/} since those
2189 won't work if the code already contains comments (C comments do not
2190 nest).
2191
2192 This works even if the code being turned off contains conditionals, but
2193 they must be entire conditionals (balanced @samp{#if} and @samp{#endif}).
2194
2195 Conversely, do not use @samp{#if 0} for comments which are not C code.
2196 Use the comment delimiters @samp{/*} and @samp{*/} instead.  The
2197 interior of @samp{#if 0} must consist of complete tokens; in particular,
2198 singlequote characters must balance.  But comments often contain
2199 unbalanced singlequote characters (known in English as apostrophes).
2200 These confuse @samp{#if 0}.  They do not confuse @samp{/*}.
2201
2202 @node Conditionals-Macros
2203 @subsection Conditionals and Macros
2204
2205 Conditionals are useful in connection with macros or assertions, because
2206 those are the only ways that an expression's value can vary from one
2207 compilation to another.  A @samp{#if} directive whose expression uses no
2208 macros or assertions is equivalent to @samp{#if 1} or @samp{#if 0}; you
2209 might as well determine which one, by computing the value of the
2210 expression yourself, and then simplify the program.
2211
2212 For example, here is a conditional that tests the expression
2213 @samp{BUFSIZE == 1020}, where @samp{BUFSIZE} must be a macro.
2214
2215 @example
2216 #if BUFSIZE == 1020
2217   printf ("Large buffers!\n");
2218 #endif /* BUFSIZE is large */
2219 @end example
2220
2221 (Programmers often wish they could test the size of a variable or data
2222 type in @samp{#if}, but this does not work.  The preprocessor does not
2223 understand @code{sizeof}, or typedef names, or even the type keywords
2224 such as @code{int}.)
2225
2226 @findex defined
2227 The special operator @samp{defined} is used in @samp{#if} expressions to
2228 test whether a certain name is defined as a macro.  Either @samp{defined
2229 @var{name}} or @samp{defined (@var{name})} is an expression whose value
2230 is 1 if @var{name} is defined as macro at the current point in the
2231 program, and 0 otherwise.  For the @samp{defined} operator it makes no
2232 difference what the definition of the macro is; all that matters is
2233 whether there is a definition.  Thus, for example,@refill
2234
2235 @example
2236 #if defined (vax) || defined (ns16000)
2237 @end example
2238
2239 @noindent
2240 would succeed if either of the names @samp{vax} and @samp{ns16000} is
2241 defined as a macro.  You can test the same condition using assertions
2242 (@pxref{Assertions}), like this:
2243
2244 @example
2245 #if #cpu (vax) || #cpu (ns16000)
2246 @end example
2247
2248 If a macro is defined and later undefined with @samp{#undef},
2249 subsequent use of the @samp{defined} operator returns 0, because
2250 the name is no longer defined.  If the macro is defined again with
2251 another @samp{#define}, @samp{defined} will recommence returning 1.
2252
2253 @findex #ifdef
2254 @findex #ifndef
2255 Conditionals that test whether just one name is defined are very common,
2256 so there are two special short conditional directives for this case.
2257
2258 @table @code
2259 @item #ifdef @var{name}
2260 is equivalent to @samp{#if defined (@var{name})}.
2261
2262 @item #ifndef @var{name}
2263 is equivalent to @samp{#if ! defined (@var{name})}.
2264 @end table
2265
2266 Macro definitions can vary between compilations for several reasons.
2267
2268 @itemize @bullet
2269 @item
2270 Some macros are predefined on each kind of machine.  For example, on a
2271 Vax, the name @samp{vax} is a predefined macro.  On other machines, it
2272 would not be defined.
2273
2274 @item
2275 Many more macros are defined by system header files.  Different
2276 systems and machines define different macros, or give them different
2277 values.  It is useful to test these macros with conditionals to avoid
2278 using a system feature on a machine where it is not implemented.
2279
2280 @item
2281 Macros are a common way of allowing users to customize a program for
2282 different machines or applications.  For example, the macro
2283 @samp{BUFSIZE} might be defined in a configuration file for your
2284 program that is included as a header file in each source file.  You
2285 would use @samp{BUFSIZE} in a preprocessing conditional in order to
2286 generate different code depending on the chosen configuration.
2287
2288 @item
2289 Macros can be defined or undefined with @samp{-D} and @samp{-U}
2290 command options when you compile the program.  You can arrange to
2291 compile the same source file into two different programs by choosing
2292 a macro name to specify which program you want, writing conditionals
2293 to test whether or how this macro is defined, and then controlling
2294 the state of the macro with compiler command options.
2295 @xref{Invocation}.
2296 @end itemize
2297
2298 @ifinfo
2299 Assertions are usually predefined, but can be defined with preprocessor
2300 directives or command-line options.
2301 @end ifinfo
2302
2303 @node Assertions
2304 @subsection Assertions
2305
2306 @cindex assertions
2307 @dfn{Assertions} are a more systematic alternative to macros in writing
2308 conditionals to test what sort of computer or system the compiled
2309 program will run on.  Assertions are usually predefined, but you can
2310 define them with preprocessing directives or command-line options.
2311
2312 @cindex predicates
2313 The macros traditionally used to describe the type of target are not
2314 classified in any way according to which question they answer; they may
2315 indicate a hardware architecture, a particular hardware model, an
2316 operating system, a particular version of an operating system, or
2317 specific configuration options.  These are jumbled together in a single
2318 namespace.  In contrast, each assertion consists of a named question and
2319 an answer.  The question is usually called the @dfn{predicate}.
2320 An assertion looks like this:
2321
2322 @example
2323 #@var{predicate} (@var{answer})
2324 @end example
2325
2326 @noindent
2327 You must use a properly formed identifier for @var{predicate}.  The
2328 value of @var{answer} can be any sequence of words; all characters are
2329 significant except for leading and trailing whitespace, and differences
2330 in internal whitespace sequences are ignored.  Thus, @samp{x + y} is
2331 different from @samp{x+y} but equivalent to @samp{x + y}.  @samp{)} is
2332 not allowed in an answer.
2333
2334 @cindex testing predicates
2335 Here is a conditional to test whether the answer @var{answer} is asserted
2336 for the predicate @var{predicate}:
2337
2338 @example
2339 #if #@var{predicate} (@var{answer})
2340 @end example
2341
2342 @noindent
2343 There may be more than one answer asserted for a given predicate.  If
2344 you omit the answer, you can test whether @emph{any} answer is asserted
2345 for @var{predicate}:
2346
2347 @example
2348 #if #@var{predicate}
2349 @end example
2350
2351 @findex #system
2352 @findex #machine
2353 @findex #cpu
2354 Most of the time, the assertions you test will be predefined assertions.
2355 GNU C provides three predefined predicates: @code{system}, @code{cpu},
2356 and @code{machine}.  @code{system} is for assertions about the type of
2357 software, @code{cpu} describes the type of computer architecture, and
2358 @code{machine} gives more information about the computer.  For example,
2359 on a GNU system, the following assertions would be true:
2360
2361 @example
2362 #system (gnu)
2363 #system (mach)
2364 #system (mach 3)
2365 #system (mach 3.@var{subversion})
2366 #system (hurd)
2367 #system (hurd @var{version})
2368 @end example
2369
2370 @noindent
2371 and perhaps others.  The alternatives with
2372 more or less version information let you ask more or less detailed
2373 questions about the type of system software.
2374
2375 On a Unix system, you would find @code{#system (unix)} and perhaps one of:
2376 @code{#system (aix)}, @code{#system (bsd)}, @code{#system (hpux)},
2377 @code{#system (lynx)}, @code{#system (mach)}, @code{#system (posix)},
2378 @code{#system (svr3)}, @code{#system (svr4)}, or @code{#system (xpg4)}
2379 with possible version numbers following.
2380
2381 Other values for @code{system} are @code{#system (mvs)}
2382 and @code{#system (vms)}.
2383
2384 @strong{Portability note:} Many Unix C compilers provide only one answer
2385 for the @code{system} assertion: @code{#system (unix)}, if they support
2386 assertions at all.  This is less than useful.
2387
2388 An assertion with a multi-word answer is completely different from several
2389 assertions with individual single-word answers.  For example, the presence
2390 of @code{system (mach 3.0)} does not mean that @code{system (3.0)} is true.
2391 It also does not directly imply @code{system (mach)}, but in GNU C, that
2392 last will normally be asserted as well.
2393
2394 The current list of possible assertion values for @code{cpu} is:
2395 @code{#cpu (a29k)}, @code{#cpu (alpha)}, @code{#cpu (arm)}, @code{#cpu
2396 (clipper)}, @code{#cpu (convex)}, @code{#cpu (elxsi)}, @code{#cpu
2397 (tron)}, @code{#cpu (h8300)}, @code{#cpu (i370)}, @code{#cpu (i386)},
2398 @code{#cpu (i860)}, @code{#cpu (i960)}, @code{#cpu (m68k)}, @code{#cpu
2399 (m88k)}, @code{#cpu (mips)}, @code{#cpu (ns32k)}, @code{#cpu (hppa)},
2400 @code{#cpu (pyr)}, @code{#cpu (ibm032)}, @code{#cpu (rs6000)},
2401 @code{#cpu (sh)}, @code{#cpu (sparc)}, @code{#cpu (spur)}, @code{#cpu
2402 (tahoe)}, @code{#cpu (vax)}, @code{#cpu (we32000)}.
2403
2404 @findex #assert
2405 You can create assertions within a C program using @samp{#assert}, like
2406 this:
2407
2408 @example
2409 #assert @var{predicate} (@var{answer})
2410 @end example
2411
2412 @noindent
2413 (Note the absence of a @samp{#} before @var{predicate}.)
2414
2415 @cindex unassert
2416 @cindex assertions, undoing
2417 @cindex retracting assertions
2418 @findex #unassert
2419 Each time you do this, you assert a new true answer for @var{predicate}.
2420 Asserting one answer does not invalidate previously asserted answers;
2421 they all remain true.  The only way to remove an assertion is with
2422 @samp{#unassert}.  @samp{#unassert} has the same syntax as
2423 @samp{#assert}.  You can also remove all assertions about
2424 @var{predicate} like this:
2425
2426 @example
2427 #unassert @var{predicate}
2428 @end example
2429
2430 You can also add or cancel assertions using command options
2431 when you run @code{gcc} or @code{cpp}.  @xref{Invocation}.
2432
2433 @node #error Directive
2434 @subsection The @samp{#error} and @samp{#warning} Directives
2435
2436 @findex #error
2437 The directive @samp{#error} causes the preprocessor to report a fatal
2438 error.  The rest of the line that follows @samp{#error} is used as the
2439 error message.  The line must consist of complete tokens.
2440
2441 You would use @samp{#error} inside of a conditional that detects a
2442 combination of parameters which you know the program does not properly
2443 support.  For example, if you know that the program will not run
2444 properly on a Vax, you might write
2445
2446 @smallexample
2447 @group
2448 #ifdef __vax__
2449 #error "Won't work on Vaxen.  See comments at get_last_object."
2450 #endif
2451 @end group
2452 @end smallexample
2453
2454 @noindent
2455 @xref{Nonstandard Predefined}, for why this works.
2456
2457 If you have several configuration parameters that must be set up by
2458 the installation in a consistent way, you can use conditionals to detect
2459 an inconsistency and report it with @samp{#error}.  For example,
2460
2461 @smallexample
2462 #if HASH_TABLE_SIZE % 2 == 0 || HASH_TABLE_SIZE % 3 == 0 \
2463     || HASH_TABLE_SIZE % 5 == 0
2464 #error HASH_TABLE_SIZE should not be divisible by a small prime
2465 #endif
2466 @end smallexample
2467
2468 @findex #warning
2469 The directive @samp{#warning} is like the directive @samp{#error}, but causes
2470 the preprocessor to issue a warning and continue preprocessing.  The rest of
2471 the line that follows @samp{#warning} is used as the warning message.
2472
2473 You might use @samp{#warning} in obsolete header files, with a message
2474 directing the user to the header file which should be used instead.
2475
2476 @node Combining Sources, Other Directives, Conditionals, Top
2477 @section Combining Source Files
2478
2479 @cindex line control
2480 One of the jobs of the C preprocessor is to inform the C compiler of where
2481 each line of C code came from: which source file and which line number.
2482
2483 C code can come from multiple source files if you use @samp{#include};
2484 both @samp{#include} and the use of conditionals and macros can cause
2485 the line number of a line in the preprocessor output to be different
2486 from the line's number in the original source file.  You will appreciate
2487 the value of making both the C compiler (in error messages) and symbolic
2488 debuggers such as GDB use the line numbers in your source file.
2489
2490 The C preprocessor builds on this feature by offering a directive by which
2491 you can control the feature explicitly.  This is useful when a file for
2492 input to the C preprocessor is the output from another program such as the
2493 @code{bison} parser generator, which operates on another file that is the
2494 true source file.  Parts of the output from @code{bison} are generated from
2495 scratch, other parts come from a standard parser file.  The rest are copied
2496 nearly verbatim from the source file, but their line numbers in the
2497 @code{bison} output are not the same as their original line numbers.
2498 Naturally you would like compiler error messages and symbolic debuggers to
2499 know the original source file and line number of each line in the
2500 @code{bison} input.
2501
2502 @findex #line
2503 @code{bison} arranges this by writing @samp{#line} directives into the output
2504 file.  @samp{#line} is a directive that specifies the original line number
2505 and source file name for subsequent input in the current preprocessor input
2506 file.  @samp{#line} has three variants:
2507
2508 @table @code
2509 @item #line @var{linenum}
2510 Here @var{linenum} is a decimal integer constant.  This specifies that
2511 the line number of the following line of input, in its original source file,
2512 was @var{linenum}.
2513
2514 @item #line @var{linenum} @var{filename}
2515 Here @var{linenum} is a decimal integer constant and @var{filename}
2516 is a string constant.  This specifies that the following line of input
2517 came originally from source file @var{filename} and its line number there
2518 was @var{linenum}.  Keep in mind that @var{filename} is not just a
2519 file name; it is surrounded by doublequote characters so that it looks
2520 like a string constant.
2521
2522 @item #line @var{anything else}
2523 @var{anything else} is checked for macro calls, which are expanded.
2524 The result should be a decimal integer constant followed optionally
2525 by a string constant, as described above.
2526 @end table
2527
2528 @samp{#line} directives alter the results of the @samp{__FILE__} and
2529 @samp{__LINE__} predefined macros from that point on.  @xref{Standard
2530 Predefined}.
2531
2532 The output of the preprocessor (which is the input for the rest of the
2533 compiler) contains directives that look much like @samp{#line} directives.
2534 They start with just @samp{#} instead of @samp{#line}, but this is
2535 followed by a line number and file name as in @samp{#line}.  @xref{Output}.
2536
2537 @node Other Directives, Output, Combining Sources, Top
2538 @section Miscellaneous Preprocessing Directives
2539
2540 @cindex null directive
2541 This section describes three additional preprocessing directives.  They are
2542 not very useful, but are mentioned for completeness.
2543
2544 The @dfn{null directive} consists of a @samp{#} followed by a Newline, with
2545 only whitespace (including comments) in between.  A null directive is
2546 understood as a preprocessing directive but has no effect on the preprocessor
2547 output.  The primary significance of the existence of the null directive is
2548 that an input line consisting of just a @samp{#} will produce no output,
2549 rather than a line of output containing just a @samp{#}.  Supposedly
2550 some old C programs contain such lines.
2551
2552 @findex #pragma
2553 The ANSI standard specifies that the effect of the @samp{#pragma}
2554 directive is implementation-defined.  In the GNU C preprocessor,
2555 @samp{#pragma} directives are not used, except for @samp{#pragma once}
2556 (@pxref{Once-Only}).  However, they are left in the preprocessor output,
2557 so they are available to the compilation pass.
2558
2559 @findex #ident
2560 The @samp{#ident} directive is supported for compatibility with certain
2561 other systems.  It is followed by a line of text.  On some systems, the
2562 text is copied into a special place in the object file; on most systems,
2563 the text is ignored and this directive has no effect.  Typically
2564 @samp{#ident} is only used in header files supplied with those systems
2565 where it is meaningful.
2566
2567 @node Output, Invocation, Other Directives, Top
2568 @section C Preprocessor Output
2569
2570 @cindex output format
2571 The output from the C preprocessor looks much like the input, except
2572 that all preprocessing directive lines have been replaced with blank lines
2573 and all comments with spaces.  Whitespace within a line is not altered;
2574 however, unless @samp{-traditional} is used, spaces may be inserted into
2575 the expansions of macro calls to prevent tokens from being concatenated.
2576
2577 Source file name and line number information is conveyed by lines of
2578 the form
2579
2580 @example
2581 # @var{linenum} @var{filename} @var{flags}
2582 @end example
2583
2584 @noindent
2585 which are inserted as needed into the middle of the input (but never
2586 within a string or character constant).  Such a line means that the
2587 following line originated in file @var{filename} at line @var{linenum}.
2588
2589 After the file name comes zero or more flags, which are @samp{1},
2590 @samp{2}, @samp{3}, or @samp{4}.  If there are multiple flags, spaces separate
2591 them.  Here is what the flags mean:
2592
2593 @table @samp
2594 @item 1
2595 This indicates the start of a new file.
2596 @item 2
2597 This indicates returning to a file (after having included another file).
2598 @item 3
2599 This indicates that the following text comes from a system header file,
2600 so certain warnings should be suppressed.
2601 @item 4
2602 This indicates that the following text should be treated as C@.
2603 @c maybe cross reference NO_IMPLICIT_EXTERN_C
2604 @end table
2605
2606 @node Invocation, Concept Index, Output, Top
2607 @section Invoking the C Preprocessor
2608 @cindex invocation of the preprocessor
2609
2610 Most often when you use the C preprocessor you will not have to invoke it
2611 explicitly: the C compiler will do so automatically.  However, the
2612 preprocessor is sometimes useful on its own.
2613
2614 @ignore
2615 @c man begin SYNOPSIS
2616 cpp [@samp{-P}] [@samp{-C}] [@samp{-gcc}] [@samp{-traditional}]
2617     [@samp{-undef}] [@samp{-trigraphs}] [@samp{-pedantic}]
2618     [@samp{-W}@var{warn}...] [@samp{-I}@var{dir}...]
2619     [@samp{-D}@var{macro}[=@var{defn}]...] [@samp{-U}@var{macro}]
2620     [@samp{-A}@var{predicate}(@var{answer})]
2621     [@samp{-M}|@samp{-MM}|@samp{-MD}|@samp{-MMD} [@samp{-MG}]]
2622     [@samp{-x} @var{language}] [@samp{-std=}@var{standard}]
2623     @var{infile} @var{outfile}
2624
2625 Only the most useful options are listed here; see below for the remainder.
2626 @c man end
2627 @c man begin SEEALSO
2628 gcc(1), as(1), ld(1), and the Info entries for @file{cpp}, @file{gcc}, and
2629 @file{binutils}.
2630 @c man end
2631 @end ignore
2632
2633 @c man begin OPTIONS
2634 The C preprocessor expects two file names as arguments, @var{infile} and
2635 @var{outfile}.  The preprocessor reads @var{infile} together with any other
2636 files it specifies with @samp{#include}.  All the output generated by the
2637 combined input files is written in @var{outfile}.
2638
2639 Either @var{infile} or @var{outfile} may be @samp{-}, which as
2640 @var{infile} means to read from standard input and as @var{outfile}
2641 means to write to standard output.  Also, if either file is omitted, it
2642 means the same as if @samp{-} had been specified for that file.
2643
2644 @cindex options
2645 Here is a table of command options accepted by the C preprocessor.
2646 These options can also be given when compiling a C program; they are
2647 passed along automatically to the preprocessor when it is invoked by the
2648 compiler.
2649
2650 @table @samp
2651 @item -P
2652 @findex -P
2653 Inhibit generation of @samp{#}-lines with line-number information in
2654 the output from the preprocessor (@pxref{Output}).  This might be
2655 useful when running the preprocessor on something that is not C code
2656 and will be sent to a program which might be confused by the
2657 @samp{#}-lines.
2658
2659 @item -C
2660 @findex -C
2661 Do not discard comments: pass them through to the output file.
2662 Comments appearing in arguments of a macro call will be copied to the
2663 output before the expansion of the macro call.
2664
2665 @item -traditional
2666 @findex -traditional
2667 Try to imitate the behavior of old-fashioned C, as opposed to ANSI C@.
2668
2669 @itemize @bullet
2670 @item
2671 Traditional macro expansion pays no attention to singlequote or
2672 doublequote characters; macro argument symbols are replaced by the
2673 argument values even when they appear within apparent string or
2674 character constants.
2675
2676 @item
2677 Traditionally, it is permissible for a macro expansion to end in the
2678 middle of a string or character constant.  The constant continues into
2679 the text surrounding the macro call.
2680
2681 @item
2682 However, traditionally the end of the line terminates a string or
2683 character constant, with no error.
2684
2685 @item
2686 In traditional C, a comment is equivalent to no text at all.  (In ANSI
2687 C, a comment counts as whitespace.)
2688
2689 @item
2690 Traditional C does not have the concept of a ``preprocessing number''.
2691 It considers @samp{1.0e+4} to be three tokens: @samp{1.0e}, @samp{+},
2692 and @samp{4}.
2693
2694 @item
2695 A macro is not suppressed within its own definition, in traditional C@.
2696 Thus, any macro that is used recursively inevitably causes an error.
2697
2698 @item
2699 The character @samp{#} has no special meaning within a macro definition
2700 in traditional C@.
2701
2702 @item
2703 In traditional C, the text at the end of a macro expansion can run
2704 together with the text after the macro call, to produce a single token.
2705 (This is impossible in ANSI C@.)
2706
2707 @item
2708 Traditionally, @samp{\} inside a macro argument suppresses the syntactic
2709 significance of the following character.
2710 @end itemize
2711
2712 @cindex Fortran
2713 @cindex unterminated
2714 Use the @samp{-traditional} option when preprocessing Fortran code,
2715 so that singlequotes and doublequotes
2716 within Fortran comment lines
2717 (which are generally not recognized as such by the preprocessor)
2718 do not cause diagnostics
2719 about unterminated character or string constants.
2720
2721 However, this option does not prevent diagnostics
2722 about unterminated comments
2723 when a C-style comment appears to start, but not end,
2724 within Fortran-style commentary.
2725
2726 So, the following Fortran comment lines are accepted with
2727 @samp{-traditional}:
2728
2729 @smallexample
2730 C This isn't an unterminated character constant
2731 C Neither is "20000000000, an octal constant
2732 C in some dialects of Fortran
2733 @end smallexample
2734
2735 However, this type of comment line will likely produce a diagnostic,
2736 or at least unexpected output from the preprocessor,
2737 due to the unterminated comment:
2738
2739 @smallexample
2740 C Some Fortran compilers accept /* as starting
2741 C an inline comment.
2742 @end smallexample
2743
2744 @cindex g77
2745 Note that @code{g77} automatically supplies
2746 the @samp{-traditional} option
2747 when it invokes the preprocessor.
2748 However, a future version of @code{g77}
2749 might use a different, more-Fortran-aware preprocessor
2750 in place of @code{cpp}.
2751
2752 @item -trigraphs
2753 @findex -trigraphs
2754 Process ANSI standard trigraph sequences.  These are three-character
2755 sequences, all starting with @samp{??}, that are defined by ANSI C to
2756 stand for single characters.  For example, @samp{??/} stands for
2757 @samp{\}, so @samp{'??/n'} is a character constant for a newline.
2758 Strictly speaking, the GNU C preprocessor does not support all
2759 programs in ANSI Standard C unless @samp{-trigraphs} is used, but if
2760 you ever notice the difference it will be with relief.
2761
2762 You don't want to know any more about trigraphs.
2763
2764 @item -pedantic
2765 @findex -pedantic
2766 Issue warnings required by the ANSI C standard in certain cases such
2767 as when text other than a comment follows @samp{#else} or @samp{#endif}.
2768
2769 @item -pedantic-errors
2770 @findex -pedantic-errors
2771 Like @samp{-pedantic}, except that errors are produced rather than
2772 warnings.
2773
2774 @item -Wcomment
2775 @findex -Wcomment
2776 @ignore
2777 @c "Not worth documenting" both singular and plural forms of this
2778 @c option, per RMS.  But also unclear which is better; hence may need to
2779 @c switch this at some future date.  pesch@cygnus.com, 2jan92.
2780 @itemx -Wcomments
2781 (Both forms have the same effect).
2782 @end ignore
2783 Warn whenever a comment-start sequence @samp{/*} appears in a @samp{/*}
2784 comment, or whenever a Backslash-Newline appears in a @samp{//} comment.
2785
2786 @item -Wtrigraphs
2787 @findex -Wtrigraphs
2788 Warn if any trigraphs are encountered (assuming they are enabled).
2789
2790 @item -Wwhite-space
2791 @findex -Wwhite-space
2792 Warn about possible white space confusion, e.g. white space between a
2793 backslash and a newline.
2794
2795 @item -Wall
2796 @findex -Wall
2797 Requests @samp{-Wcomment}, @samp{-Wtrigraphs}, and @samp{-Wwhite-space}
2798 (but not @samp{-Wtraditional} or @samp{-Wundef}).
2799
2800 @item -Wtraditional
2801 @findex -Wtraditional
2802 Warn about certain constructs that behave differently in traditional and
2803 ANSI C@.
2804
2805 @item -Wundef
2806 @findex -Wundef
2807 Warn if an undefined identifier is evaluated in an @samp{#if} directive.
2808
2809 @item -I @var{directory}
2810 @findex -I
2811 Add the directory @var{directory} to the head of the list of
2812 directories to be searched for header files (@pxref{Include Syntax}).
2813 This can be used to override a system header file, substituting your
2814 own version, since these directories are searched before the system
2815 header file directories.  If you use more than one @samp{-I} option,
2816 the directories are scanned in left-to-right order; the standard
2817 system directories come after.
2818
2819 @item -I-
2820 Any directories specified with @samp{-I} options before the @samp{-I-}
2821 option are searched only for the case of @samp{#include "@var{file}"};
2822 they are not searched for @samp{#include <@var{file}>}.
2823
2824 If additional directories are specified with @samp{-I} options after
2825 the @samp{-I-}, these directories are searched for all @samp{#include}
2826 directives.
2827
2828 In addition, the @samp{-I-} option inhibits the use of the current
2829 directory as the first search directory for @samp{#include "@var{file}"}.
2830 Therefore, the current directory is searched only if it is requested
2831 explicitly with @samp{-I.}.  Specifying both @samp{-I-} and @samp{-I.}
2832 allows you to control precisely which directories are searched before
2833 the current one and which are searched after.
2834
2835 @item -nostdinc
2836 @findex -nostdinc
2837 Do not search the standard system directories for header files.
2838 Only the directories you have specified with @samp{-I} options
2839 (and the current directory, if appropriate) are searched.
2840
2841 @item -nostdinc++
2842 @findex -nostdinc++
2843 Do not search for header files in the C++-specific standard directories,
2844 but do still search the other standard directories.
2845 (This option is used when building the C++ library.)
2846
2847 @item -remap
2848 @findex -remap
2849 When searching for a header file in a directory, remap file names if a
2850 file named @file{header.gcc} exists in that directory.  This can be used
2851 to work around limitations of file systems with file name restrictions.
2852 The @file{header.gcc} file should contain a series of lines with two
2853 tokens on each line: the first token is the name to map, and the second
2854 token is the actual name to use.
2855
2856 @item -D @var{name}
2857 @findex -D
2858 Predefine @var{name} as a macro, with definition @samp{1}.
2859
2860 @item -D @var{name}=@var{definition}
2861 Predefine @var{name} as a macro, with definition @var{definition}.
2862 There are no restrictions on the contents of @var{definition}, but if
2863 you are invoking the preprocessor from a shell or shell-like program you
2864 may need to use the shell's quoting syntax to protect characters such as
2865 spaces that have a meaning in the shell syntax.  If you use more than
2866 one @samp{-D} for the same @var{name}, the rightmost definition takes
2867 effect.
2868
2869 @item -U @var{name}
2870 @findex -U
2871 Do not predefine @var{name}.  If both @samp{-U} and @samp{-D} are
2872 specified for one name, whichever one appears later on the command line
2873 wins.
2874
2875 @item -undef
2876 @findex -undef
2877 Do not predefine any nonstandard macros.
2878
2879 @item -gcc
2880 @findex -gcc
2881 Define the macros @var{__GNUC__}, @var{__GNUC_MINOR__} and
2882 @var{__GNUC_PATCHLEVEL__}. These are defined automatically when you use
2883 @samp{gcc -E}; you can turn them off in that case with @samp{-no-gcc}.
2884
2885 @item -A @var{predicate}(@var{answer})
2886 @findex -A
2887 Make an assertion with the predicate @var{predicate} and answer
2888 @var{answer}.  @xref{Assertions}.
2889
2890 @noindent
2891 You can use @samp{-A-} to disable all predefined assertions; it also
2892 undefines all predefined macros and all macros that preceded it on the
2893 command line.
2894
2895 @item -dM
2896 @findex -dM
2897 Instead of outputting the result of preprocessing, output a list of
2898 @samp{#define} directives for all the macros defined during the
2899 execution of the preprocessor, including predefined macros.  This gives
2900 you a way of finding out what is predefined in your version of the
2901 preprocessor; assuming you have no file @samp{foo.h}, the command
2902
2903 @example
2904 touch foo.h; cpp -dM foo.h
2905 @end example
2906
2907 @noindent 
2908 will show the values of any predefined macros.
2909
2910 @item -dD
2911 @findex -dD
2912 Like @samp{-dM} except in two respects: it does @emph{not} include the
2913 predefined macros, and it outputs @emph{both} the @samp{#define}
2914 directives and the result of preprocessing.  Both kinds of output go to
2915 the standard output file.
2916
2917 @item -dI
2918 @findex -dI
2919 Output @samp{#include} directives in addition to the result of preprocessing.
2920
2921 @item -M [-MG]
2922 @findex -M
2923 Instead of outputting the result of preprocessing, output a rule
2924 suitable for @code{make} describing the dependencies of the main
2925 source file.  The preprocessor outputs one @code{make} rule containing
2926 the object file name for that source file, a colon, and the names of
2927 all the included files.  If there are many included files then the
2928 rule is split into several lines using @samp{\}-newline.
2929
2930 @samp{-MG} says to treat missing header files as generated files and assume
2931 they live in the same directory as the source file.  It must be specified
2932 in addition to @samp{-M}.
2933
2934 This feature is used in automatic updating of makefiles.
2935
2936 @item -MM [-MG]
2937 @findex -MM
2938 Like @samp{-M} but mention only the files included with @samp{#include
2939 "@var{file}"}.  System header files included with @samp{#include
2940 <@var{file}>} are omitted.
2941
2942 @item -MD @var{file}
2943 @findex -MD
2944 Like @samp{-M} but the dependency information is written to @var{file}.
2945 This is in addition to compiling the file as specified---@samp{-MD} does
2946 not inhibit ordinary compilation the way @samp{-M} does.
2947
2948 When invoking @code{gcc}, do not specify the @var{file} argument.
2949 @code{gcc} will create file names made by replacing ".c" with ".d" at
2950 the end of the input file names.
2951
2952 In Mach, you can use the utility @code{md} to merge multiple dependency
2953 files into a single dependency file suitable for using with the @samp{make}
2954 command.
2955
2956 @item -MMD @var{file}
2957 @findex -MMD
2958 Like @samp{-MD} except mention only user header files, not system
2959 header files.
2960
2961 @item -H
2962 @findex -H
2963 Print the name of each header file used, in addition to other normal
2964 activities.
2965
2966 @item -imacros @var{file}
2967 @findex -imacros
2968 Process @var{file} as input, discarding the resulting output, before
2969 processing the regular input file.  Because the output generated from
2970 @var{file} is discarded, the only effect of @samp{-imacros @var{file}}
2971 is to make the macros defined in @var{file} available for use in the
2972 main input.
2973
2974 @item -include @var{file}
2975 @findex -include
2976 Process @var{file} as input, and include all the resulting output,
2977 before processing the regular input file.  
2978
2979 @item -idirafter @var{dir}
2980 @findex -idirafter
2981 @cindex second include path
2982 Add the directory @var{dir} to the second include path.  The directories
2983 on the second include path are searched when a header file is not found
2984 in any of the directories in the main include path (the one that
2985 @samp{-I} adds to).
2986
2987 @item -iprefix @var{prefix}
2988 @findex -iprefix
2989 Specify @var{prefix} as the prefix for subsequent @samp{-iwithprefix}
2990 options.
2991
2992 @item -iwithprefix @var{dir}
2993 @findex -iwithprefix
2994 Add a directory to the second include path.  The directory's name is
2995 made by concatenating @var{prefix} and @var{dir}, where @var{prefix}
2996 was specified previously with @samp{-iprefix}.
2997
2998 @item -isystem @var{dir}
2999 @findex -isystem
3000 Add a directory to the beginning of the second include path, marking it
3001 as a system directory, so that it gets the same special treatment as
3002 is applied to the standard system directories.
3003
3004 @item -x c
3005 @itemx -x c++
3006 @itemx -x objective-c
3007 @itemx -x assembler-with-cpp
3008 @findex -x c
3009 @findex -x objective-c
3010 @findex -x assembler-with-cpp
3011 Specify the source language: C, C++, Objective-C, or assembly.  This has
3012 nothing to do with standards conformance or extensions; it merely
3013 selects which base syntax to expect.  If you give none of these options,
3014 cpp will deduce the language from the extension of the source file:
3015 @samp{.c}, @samp{.cc}, @samp{.m}, or @samp{.S}.  Some other common
3016 extensions for C++ and assembly are also recognized.  If cpp does not
3017 recognize the extension, it will treat the file as C; this is the most
3018 generic mode.
3019
3020 @strong{Note:} Previous versions of cpp accepted a @samp{-lang} option
3021 which selected both the language and the standards conformance level.
3022 This option has been removed, because it conflicts with the @samp{-l}
3023 option.
3024
3025 @item -std=@var{standard}
3026 @itemx -ansi
3027 @findex -std
3028 @findex -ansi
3029 Specify the standard to which the code should conform.  Currently cpp
3030 only knows about the standards for C; other language standards will be
3031 added in the future.
3032
3033 @var{standard}
3034 may be one of:
3035 @table @code
3036 @item iso9899:1990
3037 The ISO C standard from 1990.
3038
3039 @item iso9899:199409
3040 @itemx c89
3041 The 1990 C standard, as amended in 1994.  @samp{c89} is the customary
3042 shorthand for this version of the standard.
3043
3044 The @samp{-ansi} option is equivalent to @samp{-std=c89}.
3045
3046 @item iso9899:199x
3047 @itemx c9x
3048 The revised ISO C standard, which is expected to be promulgated some
3049 time in 1999.  It has not been approved yet, hence the @samp{x}.
3050
3051 @item gnu89
3052 The 1990 C standard plus GNU extensions.  This is the default.
3053
3054 @item gnu9x
3055 The 199x C standard plus GNU extensions.
3056 @end table
3057
3058 @item -Wp,-lint
3059 @findex -lint
3060 Look for commands to the program checker @code{lint} embedded in
3061 comments, and emit them preceded by @samp{#pragma lint}.  For example,
3062 the comment @samp{/* NOTREACHED */} becomes @samp{#pragma lint
3063 NOTREACHED}.
3064
3065 Because of the clash with @samp{-l}, you must use the awkward syntax
3066 above.  In a future release, this option will be replaced by
3067 @samp{-flint} or @samp{-Wlint}; we are not sure which yet.
3068
3069 @item -$
3070 @findex -$
3071 Forbid the use of @samp{$} in identifiers.  The C standard does not
3072 permit this, but it is a common extension.
3073 @end table
3074 @c man end
3075
3076 @node Concept Index, Index, Invocation, Top
3077 @unnumbered Concept Index
3078 @printindex cp
3079
3080 @node Index,, Concept Index, Top
3081 @unnumbered Index of Directives, Macros and Options
3082 @printindex fn
3083
3084 @contents
3085 @bye