OSDN Git Service

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