OSDN Git Service

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