Daily bump.
[official-gcc.git] / gcc / doc / cpp.texi
blob808f3c47ef601e6026dac16827a528d6ca5b48c5
1 \input texinfo
2 @setfilename cpp.info
3 @settitle The C Preprocessor
4 @setchapternewpage off
5 @c @smallbook
6 @c @cropmarks
7 @c @finalout
9 @macro copyrightnotice
10 @c man begin COPYRIGHT
11 Copyright @copyright{} 1987, 1989, 1991, 1992, 1993, 1994, 1995, 1996,
12 1997, 1998, 1999, 2000, 2001
13 Free Software Foundation, Inc.
15 Permission is granted to copy, distribute and/or modify this document
16 under the terms of the GNU Free Documentation License, Version 1.1 or
17 any later version published by the Free Software Foundation.  A copy of
18 the license is included in the
19 @c man end
20 section entitled ``GNU Free Documentation License''.
21 @ignore
22 @c man begin COPYRIGHT
23 man page gfdl(7).
24 @c man end
25 @end ignore
26 @end macro
28 @macro covertexts
29 @c man begin COPYRIGHT
30 This manual contains no Invariant Sections.  The Front-Cover Texts are
31 (a) (see below), and the Back-Cover Texts are (b) (see below).
33 (a) The FSF's Front-Cover Text is:
35      A GNU Manual
37 (b) The FSF's Back-Cover Text is:
39      You have freedom to copy and modify this GNU Manual, like GNU
40      software.  Copies published by the Free Software Foundation raise
41      funds for GNU development.
42 @c man end
43 @end macro
45 @macro gcctabopt{body}
46 @code{\body\}
47 @end macro
49 @c Create a separate index for command line options.
50 @defcodeindex op
52 @c Used in cppopts.texi and cppenv.texi.
53 @set cppmanual
55 @ifinfo
56 @dircategory Programming
57 @direntry
58 * Cpp: (cpp).                  The GNU C preprocessor.
59 @end direntry
60 @end ifinfo
62 @titlepage
63 @title The C Preprocessor
64 @subtitle Last revised April 2001
65 @subtitle for GCC version 3
66 @author Richard M. Stallman
67 @author Zachary Weinberg
68 @page
69 @c There is a fill at the bottom of the page, so we need a filll to
70 @c override it.
71 @vskip 0pt plus 1filll
72 @copyrightnotice{}
73 @covertexts{}
74 @end titlepage
75 @contents
76 @page
78 @node Top
79 @top
80 The C preprocessor implements the macro language used to transform C,
81 C++, and Objective-C programs before they are compiled.  It can also be
82 useful on its own.
84 @menu
85 * Overview::
86 * Header Files::
87 * Macros::
88 * Conditionals::
89 * Diagnostics::
90 * Line Control::
91 * Pragmas::
92 * Other Directives::
93 * Preprocessor Output::
94 * Traditional Mode::
95 * Implementation Details::
96 * Invocation::
97 * Environment Variables::
98 * GNU Free Documentation License::
99 * Option Index::
100 * Index of Directives::
101 * Concept Index::
103 @detailmenu
104  --- The Detailed Node Listing ---
106 Overview
108 * Initial processing::
109 * Tokenization::
110 * The preprocessing language::
112 Header Files
114 * Include Syntax::
115 * Include Operation::
116 * Search Path::
117 * Once-Only Headers::
118 * Computed Includes::
119 * Wrapper Headers::
120 * System Headers::
122 Macros
124 * Object-like Macros::
125 * Function-like Macros::
126 * Macro Arguments::
127 * Stringification::
128 * Concatenation::
129 * Variadic Macros::
130 * Predefined Macros::
131 * Undefining and Redefining Macros::
132 * Macro Pitfalls::
134 Predefined Macros
136 * Standard Predefined Macros::
137 * Common Predefined Macros::
138 * System-specific Predefined Macros::
139 * C++ Named Operators::
141 Macro Pitfalls
143 * Misnesting::
144 * Operator Precedence Problems::
145 * Swallowing the Semicolon::
146 * Duplication of Side Effects::
147 * Self-Referential Macros::
148 * Argument Prescan::
149 * Newlines in Arguments::
151 Conditionals
153 * Conditional Uses::
154 * Conditional Syntax::
155 * Deleted Code::
157 Conditional Syntax
159 * Ifdef::
160 * If::
161 * Defined::
162 * Else::
163 * Elif::
165 Implementation Details
167 * Implementation-defined behavior::
168 * Implementation limits::
169 * Obsolete Features::
170 * Differences from previous versions::
172 Obsolete Features
174 * Assertions::
175 * Obsolete once-only headers::
176 * Miscellaneous obsolete features::
178 @end detailmenu
179 @end menu
181 @ifnottex
182 @copyrightnotice{}
183 @covertexts{}
184 @end ifnottex
186 @node Overview
187 @chapter Overview
188 @c man begin DESCRIPTION
189 The C preprocessor, often known as @dfn{cpp}, is a @dfn{macro processor}
190 that is used automatically by the C compiler to transform your program
191 before compilation.  It is called a macro processor because it allows
192 you to define @dfn{macros}, which are brief abbreviations for longer
193 constructs.
195 The C preprocessor is intended to be used only with C, C++, and
196 Objective-C source code.  In the past, it has been abused as a general
197 text processor.  It will choke on input which does not obey C's lexical
198 rules.  For example, apostrophes will be interpreted as the beginning of
199 character constants, and cause errors.  Also, you cannot rely on it
200 preserving characteristics of the input which are not significant to
201 C-family languages.  If a Makefile is preprocessed, all the hard tabs
202 will be removed, and the Makefile will not work.
204 Having said that, you can often get away with using cpp on things which
205 are not C@.  Other Algol-ish programming languages are often safe
206 (Pascal, Ada, etc.) So is assembly, with caution.  @option{-traditional}
207 mode preserves more white space, and is otherwise more permissive.  Many
208 of the problems can be avoided by writing C or C++ style comments
209 instead of native language comments, and keeping macros simple.
211 Wherever possible, you should use a preprocessor geared to the language
212 you are writing in.  Modern versions of the GNU assembler have macro
213 facilities.  Most high level programming languages have their own
214 conditional compilation and inclusion mechanism.  If all else fails,
215 try a true general text processor, such as GNU M4.
217 C preprocessors vary in some details.  This manual discusses the GNU C
218 preprocessor, which provides a small superset of the features of ISO
219 Standard C@.  In its default mode, the GNU C preprocessor does not do a
220 few things required by the standard.  These are features which are
221 rarely, if ever, used, and may cause surprising changes to the meaning
222 of a program which does not expect them.  To get strict ISO Standard C,
223 you should use the @option{-std=c89} or @option{-std=c99} options, depending
224 on which version of the standard you want.  To get all the mandatory
225 diagnostics, you must also use @option{-pedantic}.  @xref{Invocation}.
226 @c man end
228 @menu
229 * Initial processing::
230 * Tokenization::
231 * The preprocessing language::
232 @end menu
234 @node Initial processing
235 @section Initial processing
237 The preprocessor performs a series of textual transformations on its
238 input.  These happen before all other processing.  Conceptually, they
239 happen in a rigid order, and the entire file is run through each
240 transformation before the next one begins.  GNU CPP actually does them
241 all at once, for performance reasons.  These transformations correspond
242 roughly to the first three ``phases of translation'' described in the C
243 standard.
245 @enumerate
246 @item
247 @cindex character sets
248 @cindex line endings
249 The input file is read into memory and broken into lines.
251 GNU CPP expects its input to be a text file, that is, an unstructured
252 stream of ASCII characters, with some characters indicating the end of a
253 line of text.  Extended ASCII character sets, such as ISO Latin-1 or
254 Unicode encoded in UTF-8, are also acceptable.  Character sets that are
255 not strict supersets of seven-bit ASCII will not work.  We plan to add
256 complete support for international character sets in a future release.
258 Different systems use different conventions to indicate the end of a
259 line.  GCC accepts the ASCII control sequences @kbd{LF}, @kbd{@w{CR
260 LF}}, @kbd{CR}, and @kbd{@w{LF CR}} as end-of-line markers.  The first
261 three are the canonical sequences used by Unix, DOS and VMS, and the
262 classic Mac OS (before OSX) respectively.  You may therefore safely copy
263 source code written on any of those systems to a different one and use
264 it without conversion.  (GCC may lose track of the current line number
265 if a file doesn't consistently use one convention, as sometimes happens
266 when it is edited on computers with different conventions that share a
267 network file system.)  @kbd{@w{LF CR}} is included because it has been
268 reported as an end-of-line marker under exotic conditions.
270 If the last line of any input file lacks an end-of-line marker, the end
271 of the file is considered to implicitly supply one.  The C standard says
272 that this condition provokes undefined behavior, so GCC will emit a
273 warning message.
275 @item
276 @cindex trigraphs
277 If trigraphs are enabled, they are replaced by their corresponding
278 single characters.
280 These are nine three-character sequences, all starting with @samp{??},
281 that are defined by ISO C to stand for single characters.  They permit
282 obsolete systems that lack some of C's punctuation to use C@.  For
283 example, @samp{??/} stands for @samp{\}, so @t{'??/n'} is a character
284 constant for a newline.  By default, GCC ignores trigraphs, but if you
285 request a strictly conforming mode with the @option{-std} option, then
286 it converts them.
288 Trigraphs are not popular and many compilers implement them incorrectly.
289 Portable code should not rely on trigraphs being either converted or
290 ignored.  If you use the @option{-Wall} or @option{-Wtrigraphs} options,
291 GCC will warn you when a trigraph would change the meaning of your
292 program if it were converted.
294 In a string constant, you can prevent a sequence of question marks from
295 being confused with a trigraph by inserting a backslash between the
296 question marks.  @t{"(??\?)"} is the string @samp{(???)}, not
297 @samp{(?]}.  Traditional C compilers do not recognize this idiom.
299 The nine trigraphs and their replacements are
301 @example
302 Trigraph:       ??(  ??)  ??<  ??>  ??=  ??/  ??'  ??!  ??-
303 Replacement:      [    ]    @{    @}    #    \    ^    |    ~
304 @end example
306 @item
307 @cindex continued lines
308 @cindex backslash-newline
309 Continued lines are merged into one long line.
311 A continued line is a line which ends with a backslash, @samp{\}.  The
312 backslash is removed and the following line is joined with the current
313 one.  No space is inserted, so you may split a line anywhere, even in
314 the middle of a word.  (It is generally more readable to split lines
315 only at white space.)
317 The trailing backslash on a continued line is commonly referred to as a
318 @dfn{backslash-newline}.
320 If there is white space between a backslash and the end of a line, that
321 is still a continued line.  However, as this is usually the result of an
322 editing mistake, and many compilers will not accept it as a continued
323 line, GCC will warn you about it.
325 @item
326 @cindex comments
327 @cindex line comments
328 @cindex block comments
329 All comments are replaced with single spaces.
331 There are two kinds of comments.  @dfn{Block comments} begin with
332 @samp{/*} and continue until the next @samp{*/}.  Block comments do not
333 nest:
335 @example
336 /* @r{this is} /* @r{one comment} */ @r{text outside comment}
337 @end example
339 @dfn{Line comments} begin with @samp{//} and continue to the end of the
340 current line.  Line comments do not nest either, but it does not matter,
341 because they would end in the same place anyway.
343 @example
344 // @r{this is} // @r{one comment}
345 @r{text outside comment}
346 @end example
347 @end enumerate
349 It is safe to put line comments inside block comments, or vice versa.
351 @example
352 @group
353 /* @r{block comment}
354    // @r{contains line comment}
355    @r{yet more comment}
356  */ @r{outside comment}
358 // @r{line comment} /* @r{contains block comment} */
359 @end group
360 @end example
362 But beware of commenting out one end of a block comment with a line
363 comment.
365 @example
366 @group
367  // @r{l.c.}  /* @r{block comment begins}
368     @r{oops! this isn't a comment anymore} */
369 @end group
370 @end example
372 Comments are not recognized within string literals.  @t{@w{"/* blah
373 */"}} is the string constant @samp{@w{/* blah */}}, not an empty string.
375 Line comments are not in the 1989 edition of the C standard, but they
376 are recognized by GCC as an extension.  In C++ and in the 1999 edition
377 of the C standard, they are an official part of the language.
379 Since these transformations happen before all other processing, you can
380 split a line mechanically with backslash-newline anywhere.  You can
381 comment out the end of a line.  You can continue a line comment onto the
382 next line with backslash-newline.  You can even split @samp{/*},
383 @samp{*/}, and @samp{//} onto multiple lines with backslash-newline.
384 For example:
386 @example
387 @group
390 */ # /*
391 */ defi\
392 ne FO\
393 O 10\
395 @end group
396 @end example
398 @noindent
399 is equivalent to @code{@w{#define FOO 1020}}.  All these tricks are
400 extremely confusing and should not be used in code intended to be
401 readable.
403 There is no way to prevent a backslash at the end of a line from being
404 interpreted as a backslash-newline.
406 @example
407 "foo\\
408 bar"
409 @end example
411 @noindent
412 is equivalent to @code{"foo\bar"}, not to @code{"foo\\bar"}.  To avoid
413 having to worry about this, do not use the deprecated GNU extension
414 which permits multi-line strings.  Instead, use string literal
415 concatenation:
417 @example
418    "foo\\"
419    "bar"
420 @end example
422 @noindent
423 Your program will be more portable this way, too.
425 @node Tokenization
426 @section Tokenization
428 @cindex tokens
429 @cindex preprocessing tokens
430 After the textual transformations are finished, the input file is
431 converted into a sequence of @dfn{preprocessing tokens}.  These mostly
432 correspond to the syntactic tokens used by the C compiler, but there are
433 a few differences.  White space separates tokens; it is not itself a
434 token of any kind.  Tokens do not have to be separated by white space,
435 but it is often necessary to avoid ambiguities.
437 When faced with a sequence of characters that has more than one possible
438 tokenization, the preprocessor is greedy.  It always makes each token,
439 starting from the left, as big as possible before moving on to the next
440 token.  For instance, @code{a+++++b} is interpreted as
441 @code{@w{a ++ ++ + b}}, not as @code{@w{a ++ + ++ b}}, even though the
442 latter tokenization could be part of a valid C program and the former
443 could not.
445 Once the input file is broken into tokens, the token boundaries never
446 change, except when the @samp{##} preprocessing operator is used to paste
447 tokens together.  @xref{Concatenation}.  For example,
449 @example
450 @group
451 #define foo() bar
452 foo()baz
453      @expansion{} bar baz
454 @emph{not}
455      @expansion{} barbaz
456 @end group
457 @end example
459 The compiler does not re-tokenize the preprocessor's output.  Each
460 preprocessing token becomes one compiler token.
462 @cindex identifiers
463 Preprocessing tokens fall into five broad classes: identifiers,
464 preprocessing numbers, string literals, punctuators, and other.  An
465 @dfn{identifier} is the same as an identifier in C: any sequence of
466 letters, digits, or underscores, which begins with a letter or
467 underscore.  Keywords of C have no significance to the preprocessor;
468 they are ordinary identifiers.  You can define a macro whose name is a
469 keyword, for instance.  The only identifier which can be considered a
470 preprocessing keyword is @code{defined}.  @xref{Defined}.
472 This is mostly true of other languages which use the C preprocessor.
473 However, a few of the keywords of C++ are significant even in the
474 preprocessor.  @xref{C++ Named Operators}.
476 In the 1999 C standard, identifiers may contain letters which are not
477 part of the ``basic source character set,'' at the implementation's
478 discretion (such as accented Latin letters, Greek letters, or Chinese
479 ideograms).  This may be done with an extended character set, or the
480 @samp{\u} and @samp{\U} escape sequences.  GCC does not presently
481 implement either feature in the preprocessor or the compiler.
483 As an extension, GCC treats @samp{$} as a letter.  This is for
484 compatibility with some systems, such as VMS, where @samp{$} is commonly
485 used in system-defined function and object names.  @samp{$} is not a
486 letter in strictly conforming mode, or if you specify the @option{-$}
487 option.  @xref{Invocation}.
489 @cindex numbers
490 @cindex preprocessing numbers
491 A @dfn{preprocessing number} has a rather bizarre definition.  The
492 category includes all the normal integer and floating point constants
493 one expects of C, but also a number of other things one might not
494 initially recognize as a number.  Formally, preprocessing numbers begin
495 with an optional period, a required decimal digit, and then continue
496 with any sequence of letters, digits, underscores, periods, and
497 exponents.  Exponents are the two-character sequences @samp{e+},
498 @samp{e-}, @samp{E+}, @samp{E-}, @samp{p+}, @samp{p-}, @samp{P+}, and
499 @samp{P-}.  (The exponents that begin with @samp{p} or @samp{P} are new
500 to C99.  They are used for hexadecimal floating-point constants.)
502 The purpose of this unusual definition is to isolate the preprocessor
503 from the full complexity of numeric constants.  It does not have to
504 distinguish between lexically valid and invalid floating-point numbers,
505 which is complicated.  The definition also permits you to split an
506 identifier at any position and get exactly two tokens, which can then be
507 pasted back together with the @samp{##} operator.
509 It's possible for preprocessing numbers to cause programs to be
510 misinterpreted.  For example, @code{0xE+12} is a preprocessing number
511 which does not translate to any valid numeric constant, therefore a
512 syntax error.  It does not mean @code{@w{0xE + 12}}, which is what you
513 might have intended.
515 @cindex string literals
516 @cindex string constants
517 @cindex character constants
518 @cindex header file names
519 @c the @: prevents makeinfo from turning '' into ".
520 @dfn{String literals} are string constants, character constants, and
521 header file names (the argument of @samp{#include}).@footnote{The C
522 standard uses the term @dfn{string literal} to refer only to what we are
523 calling @dfn{string constants}.}  String constants and character
524 constants are straightforward: @t{"@dots{}"} or @t{'@dots{}'}.  In
525 either case embedded quotes should be escaped with a backslash:
526 @t{'\'@:'} is the character constant for @samp{'}.  There is no limit on
527 the length of a character constant, but the value of a character
528 constant that contains more than one character is
529 implementation-defined.  @xref{Implementation Details}.
531 Header file names either look like string constants, @t{"@dots{}"}, or are
532 written with angle brackets instead, @t{<@dots{}>}.  In either case,
533 backslash is an ordinary character.  There is no way to escape the
534 closing quote or angle bracket.  The preprocessor looks for the header
535 file in different places depending on which form you use.  @xref{Include
536 Operation}.
538 In standard C, no string literal may extend past the end of a line.  GNU
539 CPP accepts multi-line string constants, but not multi-line character
540 constants or header file names.  This extension is deprecated and will
541 be removed in GCC 3.1.  You may use continued lines instead, or string
542 constant concatenation.  @xref{Differences from previous versions}.
544 @cindex punctuators
545 @cindex digraphs
546 @cindex alternative tokens
547 @dfn{Punctuators} are all the usual bits of punctuation which are
548 meaningful to C and C++.  All but three of the punctuation characters in
549 ASCII are C punctuators.  The exceptions are @samp{@@}, @samp{$}, and
550 @samp{`}.  In addition, all the two- and three-character operators are
551 punctuators.  There are also six @dfn{digraphs}, which the C++ standard
552 calls @dfn{alternative tokens}, which are merely alternate ways to spell
553 other punctuators.  This is a second attempt to work around missing
554 punctuation in obsolete systems.  It has no negative side effects,
555 unlike trigraphs, but does not cover as much ground.  The digraphs and
556 their corresponding normal punctuators are:
558 @example
559 Digraph:        <%  %>  <:  :>  %:  %:%:
560 Punctuator:      @{   @}   [   ]   #    ##
561 @end example
563 @cindex other tokens
564 Any other single character is considered ``other.'' It is passed on to
565 the preprocessor's output unmolested.  The C compiler will almost
566 certainly reject source code containing ``other'' tokens.  In ASCII, the
567 only other characters are @samp{@@}, @samp{$}, @samp{`}, and control
568 characters other than NUL (all bits zero).  (Note that @samp{$} is
569 normally considered a letter.)  All characters with the high bit set
570 (numeric range 0x7F--0xFF) are also ``other'' in the present
571 implementation.  This will change when proper support for international
572 character sets is added to GCC@.
574 NUL is a special case because of the high probability that its
575 appearance is accidental, and because it may be invisible to the user
576 (many terminals do not display NUL at all).  Within comments, NULs are
577 silently ignored, just as any other character would be.  In running
578 text, NUL is considered white space.  For example, these two directives
579 have the same meaning.
581 @example
582 #define X^@@1
583 #define X 1
584 @end example
586 @noindent
587 (where @samp{^@@} is ASCII NUL)@.  Within string or character constants,
588 NULs are preserved.  In the latter two cases the preprocessor emits a
589 warning message.
591 @node The preprocessing language
592 @section The preprocessing language
593 @cindex directives
594 @cindex preprocessing directives
595 @cindex directive line
596 @cindex directive name
598 After tokenization, the stream of tokens may simply be passed straight
599 to the compiler's parser.  However, if it contains any operations in the
600 @dfn{preprocessing language}, it will be transformed first.  This stage
601 corresponds roughly to the standard's ``translation phase 4'' and is
602 what most people think of as the preprocessor's job.
604 The preprocessing language consists of @dfn{directives} to be executed
605 and @dfn{macros} to be expanded.  Its primary capabilities are:
607 @itemize @bullet
608 @item
609 Inclusion of header files.  These are files of declarations that can be
610 substituted into your program.
612 @item
613 Macro expansion.  You can define @dfn{macros}, which are abbreviations
614 for arbitrary fragments of C code.  The preprocessor will replace the
615 macros with their definitions throughout the program.  Some macros are
616 automatically defined for you.
618 @item
619 Conditional compilation.  You can include or exclude parts of the
620 program according to various conditions.
622 @item
623 Line control.  If you use a program to combine or rearrange source files
624 into an intermediate file which is then compiled, you can use line
625 control to inform the compiler where each source line originally came
626 from.
628 @item
629 Diagnostics.  You can detect problems at compile time and issue errors
630 or warnings.
631 @end itemize
633 There are a few more, less useful, features.
635 Except for expansion of predefined macros, all these operations are
636 triggered with @dfn{preprocessing directives}.  Preprocessing directives
637 are lines in your program that start with @samp{#}.  Whitespace is
638 allowed before and after the @samp{#}.  The @samp{#} is followed by an
639 identifier, the @dfn{directive name}.  It specifies the operation to
640 perform.  Directives are commonly referred to as @samp{#@var{name}}
641 where @var{name} is the directive name.  For example, @samp{#define} is
642 the directive that defines a macro.
644 The @samp{#} which begins a directive cannot come from a macro
645 expansion.  Also, the directive name is not macro expanded.  Thus, if
646 @code{foo} is defined as a macro expanding to @code{define}, that does
647 not make @samp{#foo} a valid preprocessing directive.
649 The set of valid directive names is fixed.  Programs cannot define new
650 preprocessing directives.
652 Some directives require arguments; these make up the rest of the
653 directive line and must be separated from the directive name by
654 whitespace.  For example, @samp{#define} must be followed by a macro
655 name and the intended expansion of the macro.
657 A preprocessing directive cannot cover more than one line.  The line
658 may, however, be continued with backslash-newline, or by a block comment
659 which extends past the end of the line.  In either case, when the
660 directive is processed, the continuations have already been merged with
661 the first line to make one long line.
663 @node Header Files
664 @chapter Header Files
666 @cindex header file
667 A header file is a file containing C declarations and macro definitions
668 (@pxref{Macros}) to be shared between several source files.  You request
669 the use of a header file in your program by @dfn{including} it, with the
670 C preprocessing directive @samp{#include}.
672 Header files serve two purposes.
674 @itemize @bullet
675 @item
676 @cindex system header files
677 System header files declare the interfaces to parts of the operating
678 system.  You include them in your program to supply the definitions and
679 declarations you need to invoke system calls and libraries.
681 @item
682 Your own header files contain declarations for interfaces between the
683 source files of your program.  Each time you have a group of related
684 declarations and macro definitions all or most of which are needed in
685 several different source files, it is a good idea to create a header
686 file for them.
687 @end itemize
689 Including a header file produces the same results as copying the header
690 file into each source file that needs it.  Such copying would be
691 time-consuming and error-prone.  With a header file, the related
692 declarations appear in only one place.  If they need to be changed, they
693 can be changed in one place, and programs that include the header file
694 will automatically use the new version when next recompiled.  The header
695 file eliminates the labor of finding and changing all the copies as well
696 as the risk that a failure to find one copy will result in
697 inconsistencies within a program.
699 In C, the usual convention is to give header files names that end with
700 @file{.h}.  It is most portable to use only letters, digits, dashes, and
701 underscores in header file names, and at most one dot.
703 @menu
704 * Include Syntax::
705 * Include Operation::
706 * Search Path::
707 * Once-Only Headers::
708 * Computed Includes::
709 * Wrapper Headers::
710 * System Headers::
711 @end menu
713 @node Include Syntax
714 @section Include Syntax
716 @findex #include
717 Both user and system header files are included using the preprocessing
718 directive @samp{#include}.  It has two variants:
720 @table @code
721 @item #include <@var{file}>
722 This variant is used for system header files.  It searches for a file
723 named @var{file} in a standard list of system directories.  You can prepend
724 directories to this list with the @option{-I} option (@pxref{Invocation}).
726 @item #include "@var{file}"
727 This variant is used for header files of your own program.  It searches
728 for a file named @var{file} first in the directory containing the
729 current file, then in the same directories used for @code{<@var{file}>}.
730 @end table
732 The argument of @samp{#include}, whether delimited with quote marks or
733 angle brackets, behaves like a string constant in that comments are not
734 recognized, and macro names are not expanded.  Thus, @code{@w{#include
735 <x/*y>}} specifies inclusion of a system header file named @file{x/*y}.
737 However, if backslashes occur within @var{file}, they are considered
738 ordinary text characters, not escape characters.  None of the character
739 escape sequences appropriate to string constants in C are processed.
740 Thus, @code{@w{#include "x\n\\y"}} specifies a filename containing three
741 backslashes.  (Some systems interpret @samp{\} as a pathname separator.
742 All of these also interpret @samp{/} the same way.  It is most portable
743 to use only @samp{/}.)
745 It is an error if there is anything (other than comments) on the line
746 after the file name.
748 @node Include Operation
749 @section Include Operation
751 The @samp{#include} directive works by directing the C preprocessor to
752 scan the specified file as input before continuing with the rest of the
753 current file.  The output from the preprocessor contains the output
754 already generated, followed by the output resulting from the included
755 file, followed by the output that comes from the text after the
756 @samp{#include} directive.  For example, if you have a header file
757 @file{header.h} as follows,
759 @example
760 char *test (void);
761 @end example
763 @noindent
764 and a main program called @file{program.c} that uses the header file,
765 like this,
767 @example
768 int x;
769 #include "header.h"
772 main (void)
774   puts (test ());
776 @end example
778 @noindent
779 the compiler will see the same token stream as it would if
780 @file{program.c} read
782 @example
783 int x;
784 char *test (void);
787 main (void)
789   puts (test ());
791 @end example
793 Included files are not limited to declarations and macro definitions;
794 those are merely the typical uses.  Any fragment of a C program can be
795 included from another file.  The include file could even contain the
796 beginning of a statement that is concluded in the containing file, or
797 the end of a statement that was started in the including file.  However,
798 a comment or a string or character constant may not start in the
799 included file and finish in the including file.  An unterminated
800 comment, string constant or character constant in an included file is
801 considered to end (with an error message) at the end of the file.
803 To avoid confusion, it is best if header files contain only complete
804 syntactic units---function declarations or definitions, type
805 declarations, etc.
807 The line following the @samp{#include} directive is always treated as a
808 separate line by the C preprocessor, even if the included file lacks a
809 final newline.
811 @node Search Path
812 @section Search Path
814 GCC looks in several different places for headers.  On a normal Unix
815 system, if you do not instruct it otherwise, it will look for headers
816 requested with @code{@w{#include <@var{file}>}} in:
818 @example
819 /usr/local/include
820 /usr/lib/gcc-lib/@var{target}/@var{version}/include
821 /usr/@var{target}/include
822 /usr/include
823 @end example
825 For C++ programs, it will also look in @file{/usr/include/g++-v3},
826 first.  In the above, @var{target} is the canonical name of the system
827 GCC was configured to compile code for; often but not always the same as
828 the canonical name of the system it runs on.  @var{version} is the
829 version of GCC in use.
831 You can add to this list with the @option{-I@var{dir}} command line
832 option.  All the directories named by @option{-I} are searched, in
833 left-to-right order, @emph{before} the default directories.  You can
834 also prevent GCC from searching any of the default directories with the
835 @option{-nostdinc} option.  This is useful when you are compiling an
836 operating system kernel or some other program that does not use the
837 standard C library facilities, or the standard C library itself.
839 GCC looks for headers requested with @code{@w{#include "@var{file}"}}
840 first in the directory containing the current file, then in the same
841 places it would have looked for a header requested with angle brackets.
842 For example, if @file{/usr/include/sys/stat.h} contains
843 @code{@w{#include "types.h"}}, GCC looks for @file{types.h} first in
844 @file{/usr/include/sys}, then in its usual search path.
846 If you name a search directory with @option{-I@var{dir}} that is also a
847 system include directory, the @option{-I} wins; the directory will be
848 searched according to the @option{-I} ordering, and it will not be
849 treated as a system include directory. GCC will warn you when a system
850 include directory is hidden in this way.
852 @samp{#line} (@pxref{Line Control}) does not change GCC's idea of the
853 directory containing the current file.
855 You may put @option{-I-} at any point in your list of @option{-I} options.
856 This has two effects.  First, directories appearing before the
857 @option{-I-} in the list are searched only for headers requested with
858 quote marks.  Directories after @option{-I-} are searched for all
859 headers.  Second, the directory containing the current file is not
860 searched for anything, unless it happens to be one of the directories
861 named by an @option{-I} switch.
863 @option{-I. -I-} is not the same as no @option{-I} options at all, and does
864 not cause the same behavior for @samp{<>} includes that @samp{""}
865 includes get with no special options.  @option{-I.} searches the
866 compiler's current working directory for header files.  That may or may
867 not be the same as the directory containing the current file.
869 If you need to look for headers in a directory named @file{-}, write
870 @option{-I./-}.
872 There are several more ways to adjust the header search path.  They are
873 generally less useful.  @xref{Invocation}.
875 @node Once-Only Headers
876 @section Once-Only Headers
877 @cindex repeated inclusion
878 @cindex including just once
879 @cindex wrapper @code{#ifndef}
881 If a header file happens to be included twice, the compiler will process
882 its contents twice.  This is very likely to cause an error, e.g.@: when the
883 compiler sees the same structure definition twice.  Even if it does not,
884 it will certainly waste time.
886 The standard way to prevent this is to enclose the entire real contents
887 of the file in a conditional, like this:
889 @example
890 @group
891 /* File foo.  */
892 #ifndef FILE_FOO_SEEN
893 #define FILE_FOO_SEEN
895 @var{the entire file}
897 #endif /* !FILE_FOO_SEEN */
898 @end group
899 @end example
901 This construct is commonly known as a @dfn{wrapper #ifndef}.
902 When the header is included again, the conditional will be false,
903 because @code{FILE_FOO_SEEN} is defined.  The preprocessor will skip
904 over the entire contents of the file, and the compiler will not see it
905 twice.
907 GNU CPP optimizes even further.  It remembers when a header file has a
908 wrapper @samp{#ifndef}.  If a subsequent @samp{#include} specifies that
909 header, and the macro in the @samp{#ifndef} is still defined, it does
910 not bother to rescan the file at all.
912 You can put comments outside the wrapper.  They will not interfere with
913 this optimization.
915 @cindex controlling macro
916 @cindex guard macro
917 The macro @code{FILE_FOO_SEEN} is called the @dfn{controlling macro} or
918 @dfn{guard macro}.  In a user header file, the macro name should not
919 begin with @samp{_}.  In a system header file, it should begin with
920 @samp{__} to avoid conflicts with user programs.  In any kind of header
921 file, the macro name should contain the name of the file and some
922 additional text, to avoid conflicts with other header files.
924 @node Computed Includes
925 @section Computed Includes
926 @cindex computed includes
927 @cindex macros in include
929 Sometimes it is necessary to select one of several different header
930 files to be included into your program.  They might specify
931 configuration parameters to be used on different sorts of operating
932 systems, for instance.  You could do this with a series of conditionals,
934 @example
935 #if SYSTEM_1
936 # include "system_1.h"
937 #elif SYSTEM_2
938 # include "system_2.h"
939 #elif SYSTEM_3
940 @dots{}
941 #endif
942 @end example
944 That rapidly becomes tedious.  Instead, the preprocessor offers the
945 ability to use a macro for the header name.  This is called a
946 @dfn{computed include}.  Instead of writing a header name as the direct
947 argument of @samp{#include}, you simply put a macro name there instead:
949 @example
950 #define SYSTEM_H "system_1.h"
951 @dots{}
952 #include SYSTEM_H
953 @end example
955 @noindent
956 @code{SYSTEM_H} will be expanded, and the preprocessor will look for
957 @file{system_1.h} as if the @samp{#include} had been written that way
958 originally.  @code{SYSTEM_H} could be defined by your Makefile with a
959 @option{-D} option.
961 You must be careful when you define the macro.  @samp{#define} saves
962 tokens, not text.  The preprocessor has no way of knowing that the macro
963 will be used as the argument of @samp{#include}, so it generates
964 ordinary tokens, not a header name.  This is unlikely to cause problems
965 if you use double-quote includes, which are close enough to string
966 constants.  If you use angle brackets, however, you may have trouble.
968 The syntax of a computed include is actually a bit more general than the
969 above.  If the first non-whitespace character after @samp{#include} is
970 not @samp{"} or @samp{<}, then the entire line is macro-expanded
971 like running text would be.
973 If the line expands to a single string constant, the contents of that
974 string constant are the file to be included.  CPP does not re-examine the
975 string for embedded quotes, but neither does it process backslash
976 escapes in the string.  Therefore
978 @example
979 #define HEADER "a\"b"
980 #include HEADER
981 @end example
983 @noindent
984 looks for a file named @file{a\"b}.  CPP searches for the file according
985 to the rules for double-quoted includes.
987 If the line expands to a token stream beginning with a @samp{<} token
988 and including a @samp{>} token, then the tokens between the @samp{<} and
989 the first @samp{>} are combined to form the filename to be included.
990 Any whitespace between tokens is reduced to a single space; then any
991 space after the initial @samp{<} is retained, but a trailing space
992 before the closing @samp{>} is ignored.  CPP searches for the file
993 according to the rules for angle-bracket includes.
995 In either case, if there are any tokens on the line after the file name,
996 an error occurs and the directive is not processed.  It is also an error
997 if the result of expansion does not match either of the two expected
998 forms.
1000 These rules are implementation-defined behavior according to the C
1001 standard.  To minimize the risk of different compilers interpreting your
1002 computed includes differently, we recommend you use only a single
1003 object-like macro which expands to a string constant.  This will also
1004 minimize confusion for people reading your program.
1006 @node Wrapper Headers
1007 @section Wrapper Headers
1008 @cindex wrapper headers
1009 @cindex overriding a header file
1010 @findex #include_next
1012 Sometimes it is necessary to adjust the contents of a system-provided
1013 header file without editing it directly.  GCC's @command{fixincludes}
1014 operation does this, for example.  One way to do that would be to create
1015 a new header file with the same name and insert it in the search path
1016 before the original header.  That works fine as long as you're willing
1017 to replace the old header entirely.  But what if you want to refer to
1018 the old header from the new one?
1020 You cannot simply include the old header with @samp{#include}.  That
1021 will start from the beginning, and find your new header again.  If your
1022 header is not protected from multiple inclusion (@pxref{Once-Only
1023 Headers}), it will recurse infinitely and cause a fatal error.
1025 You could include the old header with an absolute pathname:
1026 @example
1027 #include "/usr/include/old-header.h"
1028 @end example
1029 @noindent
1030 This works, but is not clean; should the system headers ever move, you
1031 would have to edit the new headers to match.
1033 There is no way to solve this problem within the C standard, but you can
1034 use the GNU extension @samp{#include_next}.  It means, ``Include the
1035 @emph{next} file with this name.''  This directive works like
1036 @samp{#include} except in searching for the specified file: it starts
1037 searching the list of header file directories @emph{after} the directory
1038 in which the current file was found.
1040 Suppose you specify @option{-I /usr/local/include}, and the list of
1041 directories to search also includes @file{/usr/include}; and suppose
1042 both directories contain @file{signal.h}.  Ordinary @code{@w{#include
1043 <signal.h>}} finds the file under @file{/usr/local/include}.  If that
1044 file contains @code{@w{#include_next <signal.h>}}, it starts searching
1045 after that directory, and finds the file in @file{/usr/include}.
1047 @samp{#include_next} does not distinguish between @code{<@var{file}>}
1048 and @code{"@var{file}"} inclusion, nor does it check that the file you
1049 specify has the same name as the current file.  It simply looks for the
1050 file named, starting with the directory in the search path after the one
1051 where the current file was found.
1053 The use of @samp{#include_next} can lead to great confusion.  We
1054 recommend it be used only when there is no other alternative.  In
1055 particular, it should not be used in the headers belonging to a specific
1056 program; it should be used only to make global corrections along the
1057 lines of @command{fixincludes}.
1059 @node System Headers
1060 @section System Headers
1061 @cindex system header files
1063 The header files declaring interfaces to the operating system and
1064 runtime libraries often cannot be written in strictly conforming C@.
1065 Therefore, GCC gives code found in @dfn{system headers} special
1066 treatment.  All warnings, other than those generated by @samp{#warning}
1067 (@pxref{Diagnostics}), are suppressed while GCC is processing a system
1068 header.  Macros defined in a system header are immune to a few warnings
1069 wherever they are expanded.  This immunity is granted on an ad-hoc
1070 basis, when we find that a warning generates lots of false positives
1071 because of code in macros defined in system headers.
1073 Normally, only the headers found in specific directories are considered
1074 system headers.  These directories are determined when GCC is compiled.
1075 There are, however, two ways to make normal headers into system headers.
1077 The @option{-isystem} command line option adds its argument to the list of
1078 directories to search for headers, just like @option{-I}.  Any headers
1079 found in that directory will be considered system headers.
1081 All directories named by @option{-isystem} are searched @emph{after} all
1082 directories named by @option{-I}, no matter what their order was on the
1083 command line.  If the same directory is named by both @option{-I} and
1084 @option{-isystem}, @option{-I} wins; it is as if the @option{-isystem} option
1085 had never been specified at all. GCC warns you when this happens.
1087 @findex #pragma GCC system_header
1088 There is also a directive, @code{@w{#pragma GCC system_header}}, which
1089 tells GCC to consider the rest of the current include file a system
1090 header, no matter where it was found.  Code that comes before the
1091 @samp{#pragma} in the file will not be affected.  @code{@w{#pragma GCC
1092 system_header}} has no effect in the primary source file.
1094 On very old systems, some of the pre-defined system header directories
1095 get even more special treatment.  GNU C++ considers code in headers
1096 found in those directories to be surrounded by an @code{@w{extern "C"}}
1097 block.  There is no way to request this behavior with a @samp{#pragma},
1098 or from the command line.
1100 @node Macros
1101 @chapter Macros
1103 A @dfn{macro} is a fragment of code which has been given a name.
1104 Whenever the name is used, it is replaced by the contents of the macro.
1105 There are two kinds of macros.  They differ mostly in what they look
1106 like when they are used.  @dfn{Object-like} macros resemble data objects
1107 when used, @dfn{function-like} macros resemble function calls.
1109 You may define any valid identifier as a macro, even if it is a C
1110 keyword.  The preprocessor does not know anything about keywords.  This
1111 can be useful if you wish to hide a keyword such as @code{const} from an
1112 older compiler that does not understand it.  However, the preprocessor
1113 operator @code{defined} (@pxref{Defined}) can never be defined as a
1114 macro, and C++'s named operators (@pxref{C++ Named Operators}) cannot be
1115 macros when you are compiling C++.
1117 @menu
1118 * Object-like Macros::
1119 * Function-like Macros::
1120 * Macro Arguments::
1121 * Stringification::
1122 * Concatenation::
1123 * Variadic Macros::
1124 * Predefined Macros::
1125 * Undefining and Redefining Macros::
1126 * Macro Pitfalls::
1127 @end menu
1129 @node Object-like Macros
1130 @section Object-like Macros
1131 @cindex object-like macro
1132 @cindex symbolic constants
1133 @cindex manifest constants
1135 An @dfn{object-like macro} is a simple identifier which will be replaced
1136 by a code fragment.  It is called object-like because it looks like a
1137 data object in code that uses it.  They are most commonly used to give
1138 symbolic names to numeric constants.
1140 @findex #define
1141 You create macros with the @samp{#define} directive.  @samp{#define} is
1142 followed by the name of the macro and then the token sequence it should
1143 be an abbreviation for, which is variously referred to as the macro's
1144 @dfn{body}, @dfn{expansion} or @dfn{replacement list}.  For example,
1146 @example
1147 #define BUFFER_SIZE 1024
1148 @end example
1150 @noindent
1151 defines a macro named @code{BUFFER_SIZE} as an abbreviation for the
1152 token @code{1024}.  If somewhere after this @samp{#define} directive
1153 there comes a C statement of the form
1155 @example
1156 foo = (char *) malloc (BUFFER_SIZE);
1157 @end example
1159 @noindent
1160 then the C preprocessor will recognize and @dfn{expand} the macro
1161 @code{BUFFER_SIZE}.  The C compiler will see the same tokens as it would
1162 if you had written
1164 @example
1165 foo = (char *) malloc (1024);
1166 @end example
1168 By convention, macro names are written in upper case.  Programs are
1169 easier to read when it is possible to tell at a glance which names are
1170 macros.
1172 The macro's body ends at the end of the @samp{#define} line.  You may
1173 continue the definition onto multiple lines, if necessary, using
1174 backslash-newline.  When the macro is expanded, however, it will all
1175 come out on one line.  For example,
1177 @example
1178 #define NUMBERS 1, \
1179                 2, \
1180                 3
1181 int x[] = @{ NUMBERS @};
1182      @expansion{} int x[] = @{ 1, 2, 3 @};
1183 @end example
1185 @noindent
1186 The most common visible consequence of this is surprising line numbers
1187 in error messages.
1189 There is no restriction on what can go in a macro body provided it
1190 decomposes into valid preprocessing tokens.  Parentheses need not
1191 balance, and the body need not resemble valid C code.  (If it does not,
1192 you may get error messages from the C compiler when you use the macro.)
1194 The C preprocessor scans your program sequentially.  Macro definitions
1195 take effect at the place you write them.  Therefore, the following input
1196 to the C preprocessor
1198 @example
1199 foo = X;
1200 #define X 4
1201 bar = X;
1202 @end example
1204 @noindent
1205 produces
1207 @example
1208 foo = X;
1209 bar = 4;
1210 @end example
1212 When the preprocessor expands a macro name, the macro's expansion
1213 replaces the macro invocation, then the expansion is examined for more
1214 macros to expand.  For example,
1216 @example
1217 @group
1218 #define TABLESIZE BUFSIZE
1219 #define BUFSIZE 1024
1220 TABLESIZE
1221      @expansion{} BUFSIZE
1222      @expansion{} 1024
1223 @end group
1224 @end example
1226 @noindent
1227 @code{TABLESIZE} is expanded first to produce @code{BUFSIZE}, then that
1228 macro is expanded to produce the final result, @code{1024}.
1230 Notice that @code{BUFSIZE} was not defined when @code{TABLESIZE} was
1231 defined.  The @samp{#define} for @code{TABLESIZE} uses exactly the
1232 expansion you specify---in this case, @code{BUFSIZE}---and does not
1233 check to see whether it too contains macro names.  Only when you
1234 @emph{use} @code{TABLESIZE} is the result of its expansion scanned for
1235 more macro names.
1237 This makes a difference if you change the definition of @code{BUFSIZE}
1238 at some point in the source file.  @code{TABLESIZE}, defined as shown,
1239 will always expand using the definition of @code{BUFSIZE} that is
1240 currently in effect:
1242 @example
1243 #define BUFSIZE 1020
1244 #define TABLESIZE BUFSIZE
1245 #undef BUFSIZE
1246 #define BUFSIZE 37
1247 @end example
1249 @noindent
1250 Now @code{TABLESIZE} expands (in two stages) to @code{37}.
1252 If the expansion of a macro contains its own name, either directly or
1253 via intermediate macros, it is not expanded again when the expansion is
1254 examined for more macros.  This prevents infinite recursion.
1255 @xref{Self-Referential Macros}, for the precise details.
1257 @node Function-like Macros
1258 @section Function-like Macros
1259 @cindex function-like macros
1261 You can also define macros whose use looks like a function call.  These
1262 are called @dfn{function-like macros}.  To define a function-like macro,
1263 you use the same @samp{#define} directive, but you put a pair of
1264 parentheses immediately after the macro name.  For example,
1266 @example
1267 #define lang_init()  c_init()
1268 lang_init()
1269      @expansion{} c_init()
1270 @end example
1272 A function-like macro is only expanded if its name appears with a pair
1273 of parentheses after it.  If you write just the name, it is left alone.
1274 This can be useful when you have a function and a macro of the same
1275 name, and you wish to use the function sometimes.
1277 @example
1278 extern void foo(void);
1279 #define foo() /* optimized inline version */
1280 @dots{}
1281   foo();
1282   funcptr = foo;
1283 @end example
1285 Here the call to @code{foo()} will use the macro, but the function
1286 pointer will get the address of the real function.  If the macro were to
1287 be expanded, it would cause a syntax error.
1289 If you put spaces between the macro name and the parentheses in the
1290 macro definition, that does not define a function-like macro, it defines
1291 an object-like macro whose expansion happens to begin with a pair of
1292 parentheses.
1294 @example
1295 #define lang_init ()    c_init()
1296 lang_init()
1297      @expansion{} () c_init()()
1298 @end example
1300 The first two pairs of parentheses in this expansion come from the
1301 macro.  The third is the pair that was originally after the macro
1302 invocation.  Since @code{lang_init} is an object-like macro, it does not
1303 consume those parentheses.
1305 @node Macro Arguments
1306 @section Macro Arguments
1307 @cindex arguments
1308 @cindex macros with arguments
1309 @cindex arguments in macro definitions
1311 Function-like macros can take @dfn{arguments}, just like true functions.
1312 To define a macro that uses arguments, you insert @dfn{parameters}
1313 between the pair of parentheses in the macro definition that make the
1314 macro function-like.  The parameters must be valid C identifiers,
1315 separated by commas and optionally whitespace.
1317 To invoke a macro that takes arguments, you write the name of the macro
1318 followed by a list of @dfn{actual arguments} in parentheses, separated
1319 by commas.  The invocation of the macro need not be restricted to a
1320 single logical line---it can cross as many lines in the source file as
1321 you wish.  The number of arguments you give must match the number of
1322 parameters in the macro definition.  When the macro is expanded, each
1323 use of a parameter in its body is replaced by the tokens of the
1324 corresponding argument.  (You need not use all of the parameters in the
1325 macro body.)
1327 As an example, here is a macro that computes the minimum of two numeric
1328 values, as it is defined in many C programs, and some uses.
1330 @example
1331 #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
1332   x = min(a, b);          @expansion{}  x = ((a) < (b) ? (a) : (b));
1333   y = min(1, 2);          @expansion{}  y = ((1) < (2) ? (1) : (2));
1334   z = min(a + 28, *p);    @expansion{}  z = ((a + 28) < (*p) ? (a + 28) : (*p));
1335 @end example
1337 @noindent
1338 (In this small example you can already see several of the dangers of
1339 macro arguments.  @xref{Macro Pitfalls}, for detailed explanations.)
1341 Leading and trailing whitespace in each argument is dropped, and all
1342 whitespace between the tokens of an argument is reduced to a single
1343 space.  Parentheses within each argument must balance; a comma within
1344 such parentheses does not end the argument.  However, there is no
1345 requirement for square brackets or braces to balance, and they do not
1346 prevent a comma from separating arguments.  Thus,
1348 @example
1349 macro (array[x = y, x + 1])
1350 @end example
1352 @noindent
1353 passes two arguments to @code{macro}: @code{array[x = y} and @code{x +
1354 1]}.  If you want to supply @code{array[x = y, x + 1]} as an argument,
1355 you can write it as @code{array[(x = y, x + 1)]}, which is equivalent C
1356 code.
1358 All arguments to a macro are completely macro-expanded before they are
1359 substituted into the macro body.  After substitution, the complete text
1360 is scanned again for macros to expand, including the arguments.  This rule
1361 may seem strange, but it is carefully designed so you need not worry
1362 about whether any function call is actually a macro invocation.  You can
1363 run into trouble if you try to be too clever, though.  @xref{Argument
1364 Prescan}, for detailed discussion.
1366 For example, @code{min (min (a, b), c)} is first expanded to
1368 @example
1369   min (((a) < (b) ? (a) : (b)), (c))
1370 @end example
1372 @noindent
1373 and then to
1375 @example
1376 @group
1377 ((((a) < (b) ? (a) : (b))) < (c)
1378  ? (((a) < (b) ? (a) : (b)))
1379  : (c))
1380 @end group
1381 @end example
1383 @noindent
1384 (Line breaks shown here for clarity would not actually be generated.)
1386 @cindex empty macro arguments
1387 You can leave macro arguments empty; this is not an error to the
1388 preprocessor (but many macros will then expand to invalid code).
1389 You cannot leave out arguments entirely; if a macro takes two arguments,
1390 there must be exactly one comma at the top level of its argument list.
1391 Here are some silly examples using @code{min}:
1393 @example
1394 min(, b)        @expansion{} ((   ) < (b) ? (   ) : (b))
1395 min(a, )        @expansion{} ((a  ) < ( ) ? (a  ) : ( ))
1396 min(,)          @expansion{} ((   ) < ( ) ? (   ) : ( ))
1397 min((,),)       @expansion{} (((,)) < ( ) ? ((,)) : ( ))
1399 min()      @error{} macro "min" requires 2 arguments, but only 1 given
1400 min(,,)    @error{} macro "min" passed 3 arguments, but takes just 2
1401 @end example
1403 Whitespace is not a preprocessing token, so if a macro @code{foo} takes
1404 one argument, @code{@w{foo ()}} and @code{@w{foo ( )}} both supply it an
1405 empty argument.  Previous GNU preprocessor implementations and
1406 documentation were incorrect on this point, insisting that a
1407 function-like macro that takes a single argument be passed a space if an
1408 empty argument was required.
1410 Macro parameters appearing inside string literals are not replaced by
1411 their corresponding actual arguments.
1413 @example
1414 #define foo(x) x, "x"
1415 foo(bar)        @expansion{} bar, "x"
1416 @end example
1418 @node Stringification
1419 @section Stringification
1420 @cindex stringification
1421 @cindex @samp{#} operator
1423 Sometimes you may want to convert a macro argument into a string
1424 constant.  Parameters are not replaced inside string constants, but you
1425 can use the @samp{#} preprocessing operator instead.  When a macro
1426 parameter is used with a leading @samp{#}, the preprocessor replaces it
1427 with the literal text of the actual argument, converted to a string
1428 constant.  Unlike normal parameter replacement, the argument is not
1429 macro-expanded first.  This is called @dfn{stringification}.
1431 There is no way to combine an argument with surrounding text and
1432 stringify it all together.  Instead, you can write a series of adjacent
1433 string constants and stringified arguments.  The preprocessor will
1434 replace the stringified arguments with string constants.  The C
1435 compiler will then combine all the adjacent string constants into one
1436 long string.
1438 Here is an example of a macro definition that uses stringification:
1440 @example
1441 @group
1442 #define WARN_IF(EXP) \
1443 do @{ if (EXP) \
1444         fprintf (stderr, "Warning: " #EXP "\n"); @} \
1445 while (0)
1446 WARN_IF (x == 0);
1447      @expansion{} do @{ if (x == 0)
1448            fprintf (stderr, "Warning: " "x == 0" "\n"); @} while (0);
1449 @end group
1450 @end example
1452 @noindent
1453 The argument for @code{EXP} is substituted once, as-is, into the
1454 @code{if} statement, and once, stringified, into the argument to
1455 @code{fprintf}.  If @code{x} were a macro, it would be expanded in the
1456 @code{if} statement, but not in the string.
1458 The @code{do} and @code{while (0)} are a kludge to make it possible to
1459 write @code{WARN_IF (@var{arg});}, which the resemblance of
1460 @code{WARN_IF} to a function would make C programmers want to do; see
1461 @ref{Swallowing the Semicolon}.
1463 Stringification in C involves more than putting double-quote characters
1464 around the fragment.  The preprocessor backslash-escapes the quotes
1465 surrounding embedded string constants, and all backslashes within string and
1466 character constants, in order to get a valid C string constant with the
1467 proper contents.  Thus, stringifying @code{@w{p = "foo\n";}} results in
1468 @t{@w{"p = \"foo\\n\";"}}.  However, backslashes that are not inside string
1469 or character constants are not duplicated: @samp{\n} by itself
1470 stringifies to @t{"\n"}.
1472 All leading and trailing whitespace in text being stringified is
1473 ignored.  Any sequence of whitespace in the middle of the text is
1474 converted to a single space in the stringified result.  Comments are
1475 replaced by whitespace long before stringification happens, so they
1476 never appear in stringified text.
1478 There is no way to convert a macro argument into a character constant.
1480 If you want to stringify the result of expansion of a macro argument,
1481 you have to use two levels of macros.
1483 @example
1484 #define xstr(s) str(s)
1485 #define str(s) #s
1486 #define foo 4
1487 str (foo)
1488      @expansion{} "foo"
1489 xstr (foo)
1490      @expansion{} xstr (4)
1491      @expansion{} str (4)
1492      @expansion{} "4"
1493 @end example
1495 @code{s} is stringified when it is used in @code{str}, so it is not
1496 macro-expanded first.  But @code{s} is an ordinary argument to
1497 @code{xstr}, so it is completely macro-expanded before @code{xstr}
1498 itself is expanded (@pxref{Argument Prescan}).  Therefore, by the time
1499 @code{str} gets to its argument, it has already been macro-expanded.
1501 @node Concatenation
1502 @section Concatenation
1503 @cindex concatenation
1504 @cindex token pasting
1505 @cindex token concatenation
1506 @cindex @samp{##} operator
1508 It is often useful to merge two tokens into one while expanding macros.
1509 This is called @dfn{token pasting} or @dfn{token concatenation}.  The
1510 @samp{##} preprocessing operator performs token pasting.  When a macro
1511 is expanded, the two tokens on either side of each @samp{##} operator
1512 are combined into a single token, which then replaces the @samp{##} and
1513 the two original tokens in the macro expansion.  Usually both will be
1514 identifiers, or one will be an identifier and the other a preprocessing
1515 number.  When pasted, they make a longer identifier.  This isn't the
1516 only valid case.  It is also possible to concatenate two numbers (or a
1517 number and a name, such as @code{1.5} and @code{e3}) into a number.
1518 Also, multi-character operators such as @code{+=} can be formed by
1519 token pasting.
1521 However, two tokens that don't together form a valid token cannot be
1522 pasted together.  For example, you cannot concatenate @code{x} with
1523 @code{+} in either order.  If you try, the preprocessor issues a warning
1524 and emits the two tokens.  Whether it puts white space between the
1525 tokens is undefined.  It is common to find unnecessary uses of @samp{##}
1526 in complex macros.  If you get this warning, it is likely that you can
1527 simply remove the @samp{##}.
1529 Both the tokens combined by @samp{##} could come from the macro body,
1530 but you could just as well write them as one token in the first place.
1531 Token pasting is most useful when one or both of the tokens comes from a
1532 macro argument.  If either of the tokens next to an @samp{##} is a
1533 parameter name, it is replaced by its actual argument before @samp{##}
1534 executes.  As with stringification, the actual argument is not
1535 macro-expanded first.  If the argument is empty, that @samp{##} has no
1536 effect.
1538 Keep in mind that the C preprocessor converts comments to whitespace
1539 before macros are even considered.  Therefore, you cannot create a
1540 comment by concatenating @samp{/} and @samp{*}.  You can put as much
1541 whitespace between @samp{##} and its operands as you like, including
1542 comments, and you can put comments in arguments that will be
1543 concatenated.  However, it is an error if @samp{##} appears at either
1544 end of a macro body.
1546 Consider a C program that interprets named commands.  There probably
1547 needs to be a table of commands, perhaps an array of structures declared
1548 as follows:
1550 @example
1551 @group
1552 struct command
1554   char *name;
1555   void (*function) (void);
1557 @end group
1559 @group
1560 struct command commands[] =
1562   @{ "quit", quit_command @},
1563   @{ "help", help_command @},
1564   @dots{}
1566 @end group
1567 @end example
1569 It would be cleaner not to have to give each command name twice, once in
1570 the string constant and once in the function name.  A macro which takes the
1571 name of a command as an argument can make this unnecessary.  The string
1572 constant can be created with stringification, and the function name by
1573 concatenating the argument with @samp{_command}.  Here is how it is done:
1575 @example
1576 #define COMMAND(NAME)  @{ #NAME, NAME ## _command @}
1578 struct command commands[] =
1580   COMMAND (quit),
1581   COMMAND (help),
1582   @dots{}
1584 @end example
1586 @node Variadic Macros
1587 @section Variadic Macros
1588 @cindex variable number of arguments
1589 @cindex macros with variable arguments
1590 @cindex variadic macros
1592 A macro can be declared to accept a variable number of arguments much as
1593 a function can.  The syntax for defining the macro is similar to that of
1594 a function.  Here is an example:
1596 @example
1597 #define eprintf(@dots{}) fprintf (stderr, __VA_ARGS__)
1598 @end example
1600 This kind of macro is called @dfn{variadic}.  When the macro is invoked,
1601 all the tokens in its argument list after the last named argument (this
1602 macro has none), including any commas, become the @dfn{variable
1603 argument}.  This sequence of tokens replaces the identifier
1604 @code{@w{__VA_ARGS__}} in the macro body wherever it appears.  Thus, we
1605 have this expansion:
1607 @example
1608 eprintf ("%s:%d: ", input_file, lineno)
1609      @expansion{}  fprintf (stderr, "%s:%d: ", input_file, lineno)
1610 @end example
1612 The variable argument is completely macro-expanded before it is inserted
1613 into the macro expansion, just like an ordinary argument.  You may use
1614 the @samp{#} and @samp{##} operators to stringify the variable argument
1615 or to paste its leading or trailing token with another token.  (But see
1616 below for an important special case for @samp{##}.)
1618 If your macro is complicated, you may want a more descriptive name for
1619 the variable argument than @code{@w{__VA_ARGS__}}.  GNU CPP permits
1620 this, as an extension.  You may write an argument name immediately
1621 before the @samp{@dots{}}; that name is used for the variable argument.
1622 The @code{eprintf} macro above could be written
1624 @example
1625 #define eprintf(args@dots{}) fprintf (stderr, args)
1626 @end example
1628 @noindent
1629 using this extension.  You cannot use @code{__VA_ARGS__} and this
1630 extension in the same macro.
1632 You can have named arguments as well as variable arguments in a variadic
1633 macro.  We could define @code{eprintf} like this, instead:
1635 @example
1636 #define eprintf(format, @dots{}) fprintf (stderr, format, __VA_ARGS__)
1637 @end example
1639 @noindent
1640 This formulation looks more descriptive, but unfortunately it is less
1641 flexible: you must now supply at least one argument after the format
1642 string.  In standard C, you cannot omit the comma separating the named
1643 argument from the variable arguments.  Furthermore, if you leave the
1644 variable argument empty, you will get a syntax error, because
1645 there will be an extra comma after the format string.
1647 @example
1648 eprintf("success!\n", );
1649      @expansion{} fprintf(stderr, "success!\n", );
1650 @end example
1652 GNU CPP has a pair of extensions which deal with this problem.  First,
1653 you are allowed to leave the variable argument out entirely:
1655 @example
1656 eprintf ("success!\n")
1657      @expansion{} fprintf(stderr, "success!\n", );
1658 @end example
1660 @noindent
1661 Second, the @samp{##} token paste operator has a special meaning when
1662 placed between a comma and a variable argument.  If you write
1664 @example
1665 #define eprintf(format, @dots{}) fprintf (stderr, format, ##__VA_ARGS__)
1666 @end example
1668 @noindent
1669 and the variable argument is left out when the @code{eprintf} macro is
1670 used, then the comma before the @samp{##} will be deleted.  This does
1671 @emph{not} happen if you pass an empty argument, nor does it happen if
1672 the token preceding @samp{##} is anything other than a comma.
1674 @example
1675 eprintf ("success!\n")
1676      @expansion{} fprintf(stderr, "success!\n");
1677 @end example
1679 C99 mandates that the only place the identifier @code{@w{__VA_ARGS__}}
1680 can appear is in the replacement list of a variadic macro.  It may not
1681 be used as a macro name, macro argument name, or within a different type
1682 of macro.  It may also be forbidden in open text; the standard is
1683 ambiguous.  We recommend you avoid using it except for its defined
1684 purpose.
1686 Variadic macros are a new feature in C99.  GNU CPP has supported them
1687 for a long time, but only with a named variable argument
1688 (@samp{args@dots{}}, not @samp{@dots{}} and @code{@w{__VA_ARGS__}}).  If you are
1689 concerned with portability to previous versions of GCC, you should use
1690 only named variable arguments.  On the other hand, if you are concerned
1691 with portability to other conforming implementations of C99, you should
1692 use only @code{@w{__VA_ARGS__}}.
1694 Previous versions of GNU CPP implemented the comma-deletion extension
1695 much more generally.  We have restricted it in this release to minimize
1696 the differences from C99.  To get the same effect with both this and
1697 previous versions of GCC, the token preceding the special @samp{##} must
1698 be a comma, and there must be white space between that comma and
1699 whatever comes immediately before it:
1701 @example
1702 #define eprintf(format, args@dots{}) fprintf (stderr, format , ##args)
1703 @end example
1705 @noindent
1706 @xref{Differences from previous versions}, for the gory details.
1708 @node Predefined Macros
1709 @section Predefined Macros
1711 @cindex predefined macros
1712 Several object-like macros are predefined; you use them without
1713 supplying their definitions.  They fall into three classes: standard,
1714 common, and system-specific.
1716 In C++, there is a fourth category, the named operators.  They act like
1717 predefined macros, but you cannot undefine them.
1719 @menu
1720 * Standard Predefined Macros::
1721 * Common Predefined Macros::
1722 * System-specific Predefined Macros::
1723 * C++ Named Operators::
1724 @end menu
1726 @node Standard Predefined Macros
1727 @subsection Standard Predefined Macros
1728 @cindex standard predefined macros.
1730 The standard predefined macros are specified by the C and/or C++
1731 language standards, so they are available with all compilers that
1732 implement those standards.  Older compilers may not provide all of
1733 them.  Their names all start with double underscores.
1735 @table @code
1736 @item __FILE__
1737 This macro expands to the name of the current input file, in the form of
1738 a C string constant.  This is the path by which the preprocessor opened
1739 the file, not the short name specified in @samp{#include} or as the
1740 input file name argument.  For example,
1741 @code{"/usr/local/include/myheader.h"} is a possible expansion of this
1742 macro.
1744 @item __LINE__
1745 This macro expands to the current input line number, in the form of a
1746 decimal integer constant.  While we call it a predefined macro, it's
1747 a pretty strange macro, since its ``definition'' changes with each
1748 new line of source code.
1749 @end table
1751 @code{__FILE__} and @code{__LINE__} are useful in generating an error
1752 message to report an inconsistency detected by the program; the message
1753 can state the source line at which the inconsistency was detected.  For
1754 example,
1756 @example
1757 fprintf (stderr, "Internal error: "
1758                  "negative string length "
1759                  "%d at %s, line %d.",
1760          length, __FILE__, __LINE__);
1761 @end example
1763 An @samp{#include} directive changes the expansions of @code{__FILE__}
1764 and @code{__LINE__} to correspond to the included file.  At the end of
1765 that file, when processing resumes on the input file that contained
1766 the @samp{#include} directive, the expansions of @code{__FILE__} and
1767 @code{__LINE__} revert to the values they had before the
1768 @samp{#include} (but @code{__LINE__} is then incremented by one as
1769 processing moves to the line after the @samp{#include}).
1771 A @samp{#line} directive changes @code{__LINE__}, and may change
1772 @code{__FILE__} as well.  @xref{Line Control}.
1774 C99 introduces @code{__func__}, and GCC has provided @code{__FUNCTION__}
1775 for a long time.  Both of these are strings containing the name of the
1776 current function (there are slight semantic differences; see the GCC
1777 manual).  Neither of them is a macro; the preprocessor does not know the
1778 name of the current function.  They tend to be useful in conjunction
1779 with @code{__FILE__} and @code{__LINE__}, though.
1781 @table @code
1783 @item __DATE__
1784 This macro expands to a string constant that describes the date on which
1785 the preprocessor is being run.  The string constant contains eleven
1786 characters and looks like @code{@w{"Feb 12 1996"}}.  If the day of the
1787 month is less than 10, it is padded with a space on the left.
1789 @item __TIME__
1790 This macro expands to a string constant that describes the time at
1791 which the preprocessor is being run.  The string constant contains
1792 eight characters and looks like @code{"23:59:01"}.
1794 @item __STDC__
1795 In normal operation, this macro expands to the constant 1, to signify
1796 that this compiler conforms to ISO Standard C@.  If GNU CPP is used with
1797 a compiler other than GCC, this is not necessarily true; however, the
1798 preprocessor always conforms to the standard, unless the
1799 @option{-traditional} option is used.
1801 This macro is not defined if the @option{-traditional} option is used.
1803 On some hosts, the system compiler uses a different convention, where
1804 @code{__STDC__} is normally 0, but is 1 if the user specifies strict
1805 conformance to the C Standard.  GNU CPP follows the host convention when
1806 processing system header files, but when processing user files
1807 @code{__STDC__} is always 1.  This has been reported to cause problems;
1808 for instance, some versions of Solaris provide X Windows headers that
1809 expect @code{__STDC__} to be either undefined or 1.  You may be able to
1810 work around this sort of problem by using an @option{-I} option to
1811 cancel treatment of those headers as system headers.  @xref{Invocation}.
1813 @item __STDC_VERSION__
1814 This macro expands to the C Standard's version number, a long integer
1815 constant of the form @code{@var{yyyy}@var{mm}L} where @var{yyyy} and
1816 @var{mm} are the year and month of the Standard version.  This signifies
1817 which version of the C Standard the compiler conforms to.  Like
1818 @code{__STDC__}, this is not necessarily accurate for the entire
1819 implementation, unless GNU CPP is being used with GCC@.
1821 The value @code{199409L} signifies the 1989 C standard as amended in
1822 1994, which is the current default; the value @code{199901L} signifies
1823 the 1999 revision of the C standard.  Support for the 1999 revision is
1824 not yet complete.
1826 This macro is not defined if the @option{-traditional} option is used, nor
1827 when compiling C++ or Objective-C@.
1829 @item __STDC_HOSTED__
1830 This macro is defined, with value 1, if the compiler's target is a
1831 @dfn{hosted environment}.  A hosted environment has the complete
1832 facilities of the standard C library available.
1834 @item __cplusplus
1835 This macro is defined when the C++ compiler is in use.  You can use
1836 @code{__cplusplus} to test whether a header is compiled by a C compiler
1837 or a C++ compiler.  This macro is similar to @code{__STDC_VERSION__}, in
1838 that it expands to a version number.  A fully conforming implementation
1839 of the 1998 C++ standard will define this macro to @code{199711L}.  The
1840 GNU C++ compiler is not yet fully conforming, so it uses @code{1}
1841 instead.  We hope to complete our implementation in the near future.
1843 @end table
1845 @node Common Predefined Macros
1846 @subsection Common Predefined Macros
1847 @cindex common predefined macros
1849 The common predefined macros are GNU C extensions.  They are available
1850 with the same meanings regardless of the machine or operating system on
1851 which you are using GNU C@.  Their names all start with double
1852 underscores.
1854 @table @code
1856 @item __GNUC__
1857 @itemx __GNUC_MINOR__
1858 @itemx __GNUC_PATCHLEVEL__
1859 These macros are defined by all GNU compilers that use the C
1860 preprocessor: C, C++, and Objective-C@.  Their values are the major
1861 version, minor version, and patch level of the compiler, as integer
1862 constants.  For example, GCC 3.2.1 will define @code{__GNUC__} to 3,
1863 @code{__GNUC_MINOR__} to 2, and @code{__GNUC_PATCHLEVEL__} to 1.  They
1864 are defined only when the entire compiler is in use; if you invoke the
1865 preprocessor directly, they are not defined.
1867 @code{__GNUC_PATCHLEVEL__} is new to GCC 3.0; it is also present in the
1868 widely-used development snapshots leading up to 3.0 (which identify
1869 themselves as GCC 2.96 or 2.97, depending on which snapshot you have).
1871 If all you need to know is whether or not your program is being compiled
1872 by GCC, you can simply test @code{__GNUC__}.  If you need to write code
1873 which depends on a specific version, you must be more careful.  Each
1874 time the minor version is increased, the patch level is reset to zero;
1875 each time the major version is increased (which happens rarely), the
1876 minor version and patch level are reset.  If you wish to use the
1877 predefined macros directly in the conditional, you will need to write it
1878 like this:
1880 @example
1881 /* @r{Test for GCC > 3.2.0} */
1882 #if __GNUC__ > 3 || \
1883     (__GNUC__ == 3 && (__GNUC_MINOR__ > 2 || \
1884                        (__GNUC_MINOR__ == 2 && \
1885                         __GNUC_PATCHLEVEL__ > 0))
1886 @end example
1888 @noindent
1889 Another approach is to use the predefined macros to
1890 calculate a single number, then compare that against a threshold:
1892 @example
1893 #define GCC_VERSION (__GNUC__ * 10000 \
1894                      + __GNUC_MINOR__ * 100 \
1895                      + __GNUC_PATCHLEVEL__)
1896 @dots{}
1897 /* @r{Test for GCC > 3.2.0} */
1898 #if GCC_VERSION > 30200
1899 @end example
1901 @noindent
1902 Many people find this form easier to understand.
1904 @item __OBJC__
1905 This macro is defined, with value 1, when the Objective-C compiler is in
1906 use.  You can use @code{__OBJC__} to test whether a header is compiled
1907 by a C compiler or a Objective-C compiler.
1909 @item __GNUG__
1910 The GNU C++ compiler defines this.  Testing it is equivalent to
1911 testing @code{@w{(__GNUC__ && __cplusplus)}}.
1913 @item __STRICT_ANSI__
1914 GCC defines this macro if and only if the @option{-ansi} switch, or a
1915 @option{-std} switch specifying strict conformance to some version of ISO C,
1916 was specified when GCC was invoked.  It is defined to @samp{1}.
1917 This macro exists primarily to direct GNU libc's header files to
1918 restrict their definitions to the minimal set found in the 1989 C
1919 standard.
1921 @item __BASE_FILE__
1922 This macro expands to the name of the main input file, in the form
1923 of a C string constant.  This is the source file that was specified
1924 on the command line of the preprocessor or C compiler.
1926 @item __INCLUDE_LEVEL__
1927 This macro expands to a decimal integer constant that represents the
1928 depth of nesting in include files.  The value of this macro is
1929 incremented on every @samp{#include} directive and decremented at the
1930 end of every included file.  It starts out at 0, it's value within the
1931 base file specified on the command line.
1933 @item __VERSION__
1934 This macro expands to a string constant which describes the version of
1935 the compiler in use.  You should not rely on its contents having any
1936 particular form, but it can be counted on to contain at least the
1937 release number.
1939 @item __OPTIMIZE__
1940 @itemx __OPTIMIZE_SIZE__
1941 @itemx __NO_INLINE__
1942 These macros describe the compilation mode.  @code{__OPTIMIZE__} is
1943 defined in all optimizing compilations.  @code{__OPTIMIZE_SIZE__} is
1944 defined if the compiler is optimizing for size, not speed.
1945 @code{__NO_INLINE__} is defined if no functions will be inlined into
1946 their callers (when not optimizing, or when inlining has been
1947 specifically disabled by @option{-fno-inline}).
1949 These macros cause certain GNU header files to provide optimized
1950 definitions, using macros or inline functions, of system library
1951 functions.  You should not use these macros in any way unless you make
1952 sure that programs will execute with the same effect whether or not they
1953 are defined.  If they are defined, their value is 1.
1955 @item __CHAR_UNSIGNED__
1956 GCC defines this macro if and only if the data type @code{char} is
1957 unsigned on the target machine.  It exists to cause the standard header
1958 file @file{limits.h} to work correctly.  You should not use this macro
1959 yourself; instead, refer to the standard macros defined in @file{limits.h}.
1961 @item __REGISTER_PREFIX__
1962 This macro expands to a single token (not a string constant) which is
1963 the prefix applied to CPU register names in assembly language for this
1964 target.  You can use it to write assembly that is usable in multiple
1965 environments.  For example, in the @code{m68k-aout} environment it
1966 expands to nothing, but in the @code{m68k-coff} environment it expands
1967 to a single @samp{%}.
1969 @item __USER_LABEL_PREFIX__
1970 This macro expands to a single token which is the prefix applied to
1971 user labels (symbols visible to C code) in assembly.  For example, in
1972 the @code{m68k-aout} environment it expands to an @samp{_}, but in the
1973 @code{m68k-coff} environment it expands to nothing.
1975 This macro will have the correct definition even if
1976 @option{-f(no-)underscores} is in use, but it will not be correct if
1977 target-specific options that adjust this prefix are used (e.g.@: the
1978 OSF/rose @option{-mno-underscores} option).
1980 @item __SIZE_TYPE__
1981 @itemx __PTRDIFF_TYPE__
1982 @itemx __WCHAR_TYPE__
1983 @itemx __WINT_TYPE__
1984 These macros are defined to the correct underlying types for the
1985 @code{size_t}, @code{ptrdiff_t}, @code{wchar_t}, and @code{wint_t}
1986 typedefs, respectively.  They exist to make the standard header files
1987 @file{stddef.h} and @file{wchar.h} work correctly.  You should not use
1988 these macros directly; instead, include the appropriate headers and use
1989 the typedefs.
1991 @item __USING_SJLJ_EXCEPTIONS__
1992 This macro is defined, with value 1, if the compiler uses the old
1993 mechanism based on @code{setjmp} and @code{longjmp} for exception
1994 handling.
1995 @end table
1997 @node System-specific Predefined Macros
1998 @subsection System-specific Predefined Macros
2000 @cindex system-specific predefined macros
2001 @cindex predefined macros, system-specific
2002 @cindex reserved namespace
2004 The C preprocessor normally predefines several macros that indicate what
2005 type of system and machine is in use.  They are obviously different on
2006 each target supported by GCC@.  This manual, being for all systems and
2007 machines, cannot tell you what their names are, but you can use
2008 @command{cpp -dM} to see them all.  @xref{Invocation}.  All system-specific
2009 predefined macros expand to the constant 1, so you can test them with
2010 either @samp{#ifdef} or @samp{#if}.
2012 The C standard requires that all system-specific macros be part of the
2013 @dfn{reserved namespace}.  All names which begin with two underscores,
2014 or an underscore and a capital letter, are reserved for the compiler and
2015 library to use as they wish.  However, historically system-specific
2016 macros have had names with no special prefix; for instance, it is common
2017 to find @code{unix} defined on Unix systems.  For all such macros, GCC
2018 provides a parallel macro with two underscores added at the beginning
2019 and the end.  If @code{unix} is defined, @code{__unix__} will be defined
2020 too.  There will never be more than two underscores; the parallel of
2021 @code{_mips} is @code{__mips__}.
2023 When the @option{-ansi} option, or any @option{-std} option that
2024 requests strict conformance, is given to the compiler, all the
2025 system-specific predefined macros outside the reserved namespace are
2026 suppressed.  The parallel macros, inside the reserved namespace, remain
2027 defined.
2029 We are slowly phasing out all predefined macros which are outside the
2030 reserved namespace.  You should never use them in new programs, and we
2031 encourage you to correct older code to use the parallel macros whenever
2032 you find it.  We don't recommend you use the system-specific macros that
2033 are in the reserved namespace, either.  It is better in the long run to
2034 check specifically for features you need, using a tool such as
2035 @command{autoconf}.
2037 @node C++ Named Operators
2038 @subsection C++ Named Operators
2039 @cindex named operators
2040 @cindex C++ named operators
2041 @cindex iso646.h
2043 In C++, there are eleven keywords which are simply alternate spellings
2044 of operators normally written with punctuation.  These keywords are
2045 treated as such even in the preprocessor.  They function as operators in
2046 @samp{#if}, and they cannot be defined as macros or poisoned.  In C, you
2047 can request that those keywords take their C++ meaning by including
2048 @file{iso646.h}.  That header defines each one as a normal object-like
2049 macro expanding to the appropriate punctuator.
2051 These are the named operators and their corresponding punctuators:
2053 @multitable {Named Operator} {Punctuator}
2054 @item Named Operator @tab Punctuator
2055 @item @code{and}    @tab @code{&&}
2056 @item @code{and_eq} @tab @code{&=}
2057 @item @code{bitand} @tab @code{&}
2058 @item @code{bitor}  @tab @code{|}
2059 @item @code{compl}  @tab @code{~}
2060 @item @code{not}    @tab @code{!}
2061 @item @code{not_eq} @tab @code{!=}
2062 @item @code{or}     @tab @code{||}
2063 @item @code{or_eq}  @tab @code{|=}
2064 @item @code{xor}    @tab @code{^}
2065 @item @code{xor_eq} @tab @code{^=}
2066 @end multitable
2068 @node Undefining and Redefining Macros
2069 @section Undefining and Redefining Macros
2070 @cindex undefining macros
2071 @cindex redefining macros
2072 @findex #undef
2074 If a macro ceases to be useful, it may be @dfn{undefined} with the
2075 @samp{#undef} directive.  @samp{#undef} takes a single argument, the
2076 name of the macro to undefine.  You use the bare macro name, even if the
2077 macro is function-like.  It is an error if anything appears on the line
2078 after the macro name.  @samp{#undef} has no effect if the name is not a
2079 macro.
2081 @example
2082 #define FOO 4
2083 x = FOO;        @expansion{} x = 4;
2084 #undef FOO
2085 x = FOO;        @expansion{} x = FOO;
2086 @end example
2088 Once a macro has been undefined, that identifier may be @dfn{redefined}
2089 as a macro by a subsequent @samp{#define} directive.  The new definition
2090 need not have any resemblance to the old definition.
2092 However, if an identifier which is currently a macro is redefined, then
2093 the new definition must be @dfn{effectively the same} as the old one.
2094 Two macro definitions are effectively the same if:
2095 @itemize @bullet
2096 @item Both are the same type of macro (object- or function-like).
2097 @item All the tokens of the replacement list are the same.
2098 @item If there are any parameters, they are the same.
2099 @item Whitespace appears in the same places in both.  It need not be
2100 exactly the same amount of whitespace, though.  Remember that comments
2101 count as whitespace.
2102 @end itemize
2104 @noindent
2105 These definitions are effectively the same:
2106 @example
2107 #define FOUR (2 + 2)
2108 #define FOUR         (2    +    2)
2109 #define FOUR (2 /* two */ + 2)
2110 @end example
2111 @noindent
2112 but these are not:
2113 @example
2114 #define FOUR (2 + 2)
2115 #define FOUR ( 2+2 )
2116 #define FOUR (2 * 2)
2117 #define FOUR(score,and,seven,years,ago) (2 + 2)
2118 @end example
2120 If a macro is redefined with a definition that is not effectively the
2121 same as the old one, the preprocessor issues a warning and changes the
2122 macro to use the new definition.  If the new definition is effectively
2123 the same, the redefinition is silently ignored.  This allows, for
2124 instance, two different headers to define a common macro.  The
2125 preprocessor will only complain if the definitions do not match.
2127 @node Macro Pitfalls
2128 @section Macro Pitfalls
2129 @cindex problems with macros
2130 @cindex pitfalls of macros
2132 In this section we describe some special rules that apply to macros and
2133 macro expansion, and point out certain cases in which the rules have
2134 counter-intuitive consequences that you must watch out for.
2136 @menu
2137 * Misnesting::
2138 * Operator Precedence Problems::
2139 * Swallowing the Semicolon::
2140 * Duplication of Side Effects::
2141 * Self-Referential Macros::
2142 * Argument Prescan::
2143 * Newlines in Arguments::
2144 @end menu
2146 @node Misnesting
2147 @subsection Misnesting
2149 When a macro is called with arguments, the arguments are substituted
2150 into the macro body and the result is checked, together with the rest of
2151 the input file, for more macro calls.  It is possible to piece together
2152 a macro call coming partially from the macro body and partially from the
2153 arguments.  For example,
2155 @example
2156 #define twice(x) (2*(x))
2157 #define call_with_1(x) x(1)
2158 call_with_1 (twice)
2159      @expansion{} twice(1)
2160      @expansion{} (2*(1))
2161 @end example
2163 Macro definitions do not have to have balanced parentheses.  By writing
2164 an unbalanced open parenthesis in a macro body, it is possible to create
2165 a macro call that begins inside the macro body but ends outside of it.
2166 For example,
2168 @example
2169 #define strange(file) fprintf (file, "%s %d",
2170 @dots{}
2171 strange(stderr) p, 35)
2172      @expansion{} fprintf (stderr, "%s %d", p, 35)
2173 @end example
2175 The ability to piece together a macro call can be useful, but the use of
2176 unbalanced open parentheses in a macro body is just confusing, and
2177 should be avoided.
2179 @node Operator Precedence Problems
2180 @subsection Operator Precedence Problems
2181 @cindex parentheses in macro bodies
2183 You may have noticed that in most of the macro definition examples shown
2184 above, each occurrence of a macro argument name had parentheses around
2185 it.  In addition, another pair of parentheses usually surround the
2186 entire macro definition.  Here is why it is best to write macros that
2187 way.
2189 Suppose you define a macro as follows,
2191 @example
2192 #define ceil_div(x, y) (x + y - 1) / y
2193 @end example
2195 @noindent
2196 whose purpose is to divide, rounding up.  (One use for this operation is
2197 to compute how many @code{int} objects are needed to hold a certain
2198 number of @code{char} objects.)  Then suppose it is used as follows:
2200 @example
2201 a = ceil_div (b & c, sizeof (int));
2202      @expansion{} a = (b & c + sizeof (int) - 1) / sizeof (int);
2203 @end example
2205 @noindent
2206 This does not do what is intended.  The operator-precedence rules of
2207 C make it equivalent to this:
2209 @example
2210 a = (b & (c + sizeof (int) - 1)) / sizeof (int);
2211 @end example
2213 @noindent
2214 What we want is this:
2216 @example
2217 a = ((b & c) + sizeof (int) - 1)) / sizeof (int);
2218 @end example
2220 @noindent
2221 Defining the macro as
2223 @example
2224 #define ceil_div(x, y) ((x) + (y) - 1) / (y)
2225 @end example
2227 @noindent
2228 provides the desired result.
2230 Unintended grouping can result in another way.  Consider @code{sizeof
2231 ceil_div(1, 2)}.  That has the appearance of a C expression that would
2232 compute the size of the type of @code{ceil_div (1, 2)}, but in fact it
2233 means something very different.  Here is what it expands to:
2235 @example
2236 sizeof ((1) + (2) - 1) / (2)
2237 @end example
2239 @noindent
2240 This would take the size of an integer and divide it by two.  The
2241 precedence rules have put the division outside the @code{sizeof} when it
2242 was intended to be inside.
2244 Parentheses around the entire macro definition prevent such problems.
2245 Here, then, is the recommended way to define @code{ceil_div}:
2247 @example
2248 #define ceil_div(x, y) (((x) + (y) - 1) / (y))
2249 @end example
2251 @node Swallowing the Semicolon
2252 @subsection Swallowing the Semicolon
2253 @cindex semicolons (after macro calls)
2255 Often it is desirable to define a macro that expands into a compound
2256 statement.  Consider, for example, the following macro, that advances a
2257 pointer (the argument @code{p} says where to find it) across whitespace
2258 characters:
2260 @example
2261 #define SKIP_SPACES(p, limit)  \
2262 @{ char *lim = (limit);         \
2263   while (p < lim) @{            \
2264     if (*p++ != ' ') @{         \
2265       p--; break; @}@}@}
2266 @end example
2268 @noindent
2269 Here backslash-newline is used to split the macro definition, which must
2270 be a single logical line, so that it resembles the way such code would
2271 be laid out if not part of a macro definition.
2273 A call to this macro might be @code{SKIP_SPACES (p, lim)}.  Strictly
2274 speaking, the call expands to a compound statement, which is a complete
2275 statement with no need for a semicolon to end it.  However, since it
2276 looks like a function call, it minimizes confusion if you can use it
2277 like a function call, writing a semicolon afterward, as in
2278 @code{SKIP_SPACES (p, lim);}
2280 This can cause trouble before @code{else} statements, because the
2281 semicolon is actually a null statement.  Suppose you write
2283 @example
2284 if (*p != 0)
2285   SKIP_SPACES (p, lim);
2286 else @dots{}
2287 @end example
2289 @noindent
2290 The presence of two statements---the compound statement and a null
2291 statement---in between the @code{if} condition and the @code{else}
2292 makes invalid C code.
2294 The definition of the macro @code{SKIP_SPACES} can be altered to solve
2295 this problem, using a @code{do @dots{} while} statement.  Here is how:
2297 @example
2298 #define SKIP_SPACES(p, limit)     \
2299 do @{ char *lim = (limit);         \
2300      while (p < lim) @{            \
2301        if (*p++ != ' ') @{         \
2302          p--; break; @}@}@}          \
2303 while (0)
2304 @end example
2306 Now @code{SKIP_SPACES (p, lim);} expands into
2308 @example
2309 do @{@dots{}@} while (0);
2310 @end example
2312 @noindent
2313 which is one statement.  The loop executes exactly once; most compilers
2314 generate no extra code for it.
2316 @node Duplication of Side Effects
2317 @subsection Duplication of Side Effects
2319 @cindex side effects (in macro arguments)
2320 @cindex unsafe macros
2321 Many C programs define a macro @code{min}, for ``minimum'', like this:
2323 @example
2324 #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
2325 @end example
2327 When you use this macro with an argument containing a side effect,
2328 as shown here,
2330 @example
2331 next = min (x + y, foo (z));
2332 @end example
2334 @noindent
2335 it expands as follows:
2337 @example
2338 next = ((x + y) < (foo (z)) ? (x + y) : (foo (z)));
2339 @end example
2341 @noindent
2342 where @code{x + y} has been substituted for @code{X} and @code{foo (z)}
2343 for @code{Y}.
2345 The function @code{foo} is used only once in the statement as it appears
2346 in the program, but the expression @code{foo (z)} has been substituted
2347 twice into the macro expansion.  As a result, @code{foo} might be called
2348 two times when the statement is executed.  If it has side effects or if
2349 it takes a long time to compute, the results might not be what you
2350 intended.  We say that @code{min} is an @dfn{unsafe} macro.
2352 The best solution to this problem is to define @code{min} in a way that
2353 computes the value of @code{foo (z)} only once.  The C language offers
2354 no standard way to do this, but it can be done with GNU extensions as
2355 follows:
2357 @example
2358 #define min(X, Y)                \
2359 (@{ typeof (X) x_ = (X);          \
2360    typeof (Y) y_ = (Y);          \
2361    (x_ < y_) ? x_ : y_; @})
2362 @end example
2364 The @samp{(@{ @dots{} @})} notation produces a compound statement that
2365 acts as an expression.  Its value is the value of its last statement.
2366 This permits us to define local variables and assign each argument to
2367 one.  The local variables have underscores after their names to reduce
2368 the risk of conflict with an identifier of wider scope (it is impossible
2369 to avoid this entirely).  Now each argument is evaluated exactly once.
2371 If you do not wish to use GNU C extensions, the only solution is to be
2372 careful when @emph{using} the macro @code{min}.  For example, you can
2373 calculate the value of @code{foo (z)}, save it in a variable, and use
2374 that variable in @code{min}:
2376 @example
2377 @group
2378 #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
2379 @dots{}
2381   int tem = foo (z);
2382   next = min (x + y, tem);
2384 @end group
2385 @end example
2387 @noindent
2388 (where we assume that @code{foo} returns type @code{int}).
2390 @node Self-Referential Macros
2391 @subsection Self-Referential Macros
2392 @cindex self-reference
2394 A @dfn{self-referential} macro is one whose name appears in its
2395 definition.  Recall that all macro definitions are rescanned for more
2396 macros to replace.  If the self-reference were considered a use of the
2397 macro, it would produce an infinitely large expansion.  To prevent this,
2398 the self-reference is not considered a macro call.  It is passed into
2399 the preprocessor output unchanged.  Let's consider an example:
2401 @example
2402 #define foo (4 + foo)
2403 @end example
2405 @noindent
2406 where @code{foo} is also a variable in your program.
2408 Following the ordinary rules, each reference to @code{foo} will expand
2409 into @code{(4 + foo)}; then this will be rescanned and will expand into
2410 @code{(4 + (4 + foo))}; and so on until the computer runs out of memory.
2412 The self-reference rule cuts this process short after one step, at
2413 @code{(4 + foo)}.  Therefore, this macro definition has the possibly
2414 useful effect of causing the program to add 4 to the value of @code{foo}
2415 wherever @code{foo} is referred to.
2417 In most cases, it is a bad idea to take advantage of this feature.  A
2418 person reading the program who sees that @code{foo} is a variable will
2419 not expect that it is a macro as well.  The reader will come across the
2420 identifier @code{foo} in the program and think its value should be that
2421 of the variable @code{foo}, whereas in fact the value is four greater.
2423 One common, useful use of self-reference is to create a macro which
2424 expands to itself.  If you write
2426 @example
2427 #define EPERM EPERM
2428 @end example
2430 @noindent
2431 then the macro @code{EPERM} expands to @code{EPERM}.  Effectively, it is
2432 left alone by the preprocessor whenever it's used in running text.  You
2433 can tell that it's a macro with @samp{#ifdef}.  You might do this if you
2434 want to define numeric constants with an @code{enum}, but have
2435 @samp{#ifdef} be true for each constant.
2437 If a macro @code{x} expands to use a macro @code{y}, and the expansion of
2438 @code{y} refers to the macro @code{x}, that is an @dfn{indirect
2439 self-reference} of @code{x}.  @code{x} is not expanded in this case
2440 either.  Thus, if we have
2442 @example
2443 #define x (4 + y)
2444 #define y (2 * x)
2445 @end example
2447 @noindent
2448 then @code{x} and @code{y} expand as follows:
2450 @example
2451 @group
2452 x    @expansion{} (4 + y)
2453      @expansion{} (4 + (2 * x))
2455 y    @expansion{} (2 * x)
2456      @expansion{} (2 * (4 + y))
2457 @end group
2458 @end example
2460 @noindent
2461 Each macro is expanded when it appears in the definition of the other
2462 macro, but not when it indirectly appears in its own definition.
2464 @node Argument Prescan
2465 @subsection Argument Prescan
2466 @cindex expansion of arguments
2467 @cindex macro argument expansion
2468 @cindex prescan of macro arguments
2470 Macro arguments are completely macro-expanded before they are
2471 substituted into a macro body, unless they are stringified or pasted
2472 with other tokens.  After substitution, the entire macro body, including
2473 the substituted arguments, is scanned again for macros to be expanded.
2474 The result is that the arguments are scanned @emph{twice} to expand
2475 macro calls in them.
2477 Most of the time, this has no effect.  If the argument contained any
2478 macro calls, they are expanded during the first scan.  The result
2479 therefore contains no macro calls, so the second scan does not change
2480 it.  If the argument were substituted as given, with no prescan, the
2481 single remaining scan would find the same macro calls and produce the
2482 same results.
2484 You might expect the double scan to change the results when a
2485 self-referential macro is used in an argument of another macro
2486 (@pxref{Self-Referential Macros}): the self-referential macro would be
2487 expanded once in the first scan, and a second time in the second scan.
2488 However, this is not what happens.  The self-references that do not
2489 expand in the first scan are marked so that they will not expand in the
2490 second scan either.
2492 You might wonder, ``Why mention the prescan, if it makes no difference?
2493 And why not skip it and make the preprocessor faster?''  The answer is
2494 that the prescan does make a difference in three special cases:
2496 @itemize @bullet
2497 @item
2498 Nested calls to a macro.
2500 We say that @dfn{nested} calls to a macro occur when a macro's argument
2501 contains a call to that very macro.  For example, if @code{f} is a macro
2502 that expects one argument, @code{f (f (1))} is a nested pair of calls to
2503 @code{f}.  The desired expansion is made by expanding @code{f (1)} and
2504 substituting that into the definition of @code{f}.  The prescan causes
2505 the expected result to happen.  Without the prescan, @code{f (1)} itself
2506 would be substituted as an argument, and the inner use of @code{f} would
2507 appear during the main scan as an indirect self-reference and would not
2508 be expanded.
2510 @item
2511 Macros that call other macros that stringify or concatenate.
2513 If an argument is stringified or concatenated, the prescan does not
2514 occur.  If you @emph{want} to expand a macro, then stringify or
2515 concatenate its expansion, you can do that by causing one macro to call
2516 another macro that does the stringification or concatenation.  For
2517 instance, if you have
2519 @example
2520 #define AFTERX(x) X_ ## x
2521 #define XAFTERX(x) AFTERX(x)
2522 #define TABLESIZE 1024
2523 #define BUFSIZE TABLESIZE
2524 @end example
2526 then @code{AFTERX(BUFSIZE)} expands to @code{X_BUFSIZE}, and
2527 @code{XAFTERX(BUFSIZE)} expands to @code{X_1024}.  (Not to
2528 @code{X_TABLESIZE}.  Prescan always does a complete expansion.)
2530 @item
2531 Macros used in arguments, whose expansions contain unshielded commas.
2533 This can cause a macro expanded on the second scan to be called with the
2534 wrong number of arguments.  Here is an example:
2536 @example
2537 #define foo  a,b
2538 #define bar(x) lose(x)
2539 #define lose(x) (1 + (x))
2540 @end example
2542 We would like @code{bar(foo)} to turn into @code{(1 + (foo))}, which
2543 would then turn into @code{(1 + (a,b))}.  Instead, @code{bar(foo)}
2544 expands into @code{lose(a,b)}, and you get an error because @code{lose}
2545 requires a single argument.  In this case, the problem is easily solved
2546 by the same parentheses that ought to be used to prevent misnesting of
2547 arithmetic operations:
2549 @example
2550 #define foo (a,b)
2551 @exdent or
2552 #define bar(x) lose((x))
2553 @end example
2555 The extra pair of parentheses prevents the comma in @code{foo}'s
2556 definition from being interpreted as an argument separator.
2558 @end itemize
2560 @node Newlines in Arguments
2561 @subsection Newlines in Arguments
2562 @cindex newlines in macro arguments
2564 The invocation of a function-like macro can extend over many logical
2565 lines.  However, in the present implementation, the entire expansion
2566 comes out on one line.  Thus line numbers emitted by the compiler or
2567 debugger refer to the line the invocation started on, which might be
2568 different to the line containing the argument causing the problem.
2570 Here is an example illustrating this:
2572 @example
2573 #define ignore_second_arg(a,b,c) a; c
2575 ignore_second_arg (foo (),
2576                    ignored (),
2577                    syntax error);
2578 @end example
2580 @noindent
2581 The syntax error triggered by the tokens @code{syntax error} results in
2582 an error message citing line three---the line of ignore_second_arg---
2583 even though the problematic code comes from line five.
2585 We consider this a bug, and intend to fix it in the near future.
2587 @node Conditionals
2588 @chapter Conditionals
2589 @cindex conditionals
2591 A @dfn{conditional} is a directive that instructs the preprocessor to
2592 select whether or not to include a chunk of code in the final token
2593 stream passed to the compiler.  Preprocessor conditionals can test
2594 arithmetic expressions, or whether a name is defined as a macro, or both
2595 simultaneously using the special @code{defined} operator.
2597 A conditional in the C preprocessor resembles in some ways an @code{if}
2598 statement in C, but it is important to understand the difference between
2599 them.  The condition in an @code{if} statement is tested during the
2600 execution of your program.  Its purpose is to allow your program to
2601 behave differently from run to run, depending on the data it is
2602 operating on.  The condition in a preprocessing conditional directive is
2603 tested when your program is compiled.  Its purpose is to allow different
2604 code to be included in the program depending on the situation at the
2605 time of compilation.
2607 However, the distinction is becoming less clear.  Modern compilers often
2608 do test @code{if} statements when a program is compiled, if their
2609 conditions are known not to vary at run time, and eliminate code which
2610 can never be executed.  If you can count on your compiler to do this,
2611 you may find that your program is more readable if you use @code{if}
2612 statements with constant conditions (perhaps determined by macros).  Of
2613 course, you can only use this to exclude code, not type definitions or
2614 other preprocessing directives, and you can only do it if the code
2615 remains syntactically valid when it is not to be used.
2617 GCC version 3 eliminates this kind of never-executed code even when
2618 not optimizing.  Older versions did it only when optimizing.
2620 @menu
2621 * Conditional Uses::
2622 * Conditional Syntax::
2623 * Deleted Code::
2624 @end menu
2626 @node Conditional Uses
2627 @section Conditional Uses
2629 There are three general reasons to use a conditional.
2631 @itemize @bullet
2632 @item
2633 A program may need to use different code depending on the machine or
2634 operating system it is to run on.  In some cases the code for one
2635 operating system may be erroneous on another operating system; for
2636 example, it might refer to data types or constants that do not exist on
2637 the other system.  When this happens, it is not enough to avoid
2638 executing the invalid code.  Its mere presence will cause the compiler
2639 to reject the program.  With a preprocessing conditional, the offending
2640 code can be effectively excised from the program when it is not valid.
2642 @item
2643 You may want to be able to compile the same source file into two
2644 different programs.  One version might make frequent time-consuming
2645 consistency checks on its intermediate data, or print the values of
2646 those data for debugging, and the other not.
2648 @item
2649 A conditional whose condition is always false is one way to exclude code
2650 from the program but keep it as a sort of comment for future reference.
2651 @end itemize
2653 Simple programs that do not need system-specific logic or complex
2654 debugging hooks generally will not need to use preprocessing
2655 conditionals.
2657 @node Conditional Syntax
2658 @section Conditional Syntax
2660 @findex #if
2661 A conditional in the C preprocessor begins with a @dfn{conditional
2662 directive}: @samp{#if}, @samp{#ifdef} or @samp{#ifndef}.
2664 @menu
2665 * Ifdef::
2666 * If::
2667 * Defined::
2668 * Else::
2669 * Elif::
2670 @end menu
2672 @node Ifdef
2673 @subsection Ifdef
2674 @findex #ifdef
2675 @findex #endif
2677 The simplest sort of conditional is
2679 @example
2680 @group
2681 #ifdef @var{MACRO}
2683 @var{controlled text}
2685 #endif /* @var{MACRO} */
2686 @end group
2687 @end example
2689 @cindex conditional group
2690 This block is called a @dfn{conditional group}.  @var{controlled text}
2691 will be included in the output of the preprocessor if and only if
2692 @var{MACRO} is defined.  We say that the conditional @dfn{succeeds} if
2693 @var{MACRO} is defined, @dfn{fails} if it is not.
2695 The @var{controlled text} inside of a conditional can include
2696 preprocessing directives.  They are executed only if the conditional
2697 succeeds.  You can nest conditional groups inside other conditional
2698 groups, but they must be completely nested.  In other words,
2699 @samp{#endif} always matches the nearest @samp{#ifdef} (or
2700 @samp{#ifndef}, or @samp{#if}).  Also, you cannot start a conditional
2701 group in one file and end it in another.
2703 Even if a conditional fails, the @var{controlled text} inside it is
2704 still run through initial transformations and tokenization.  Therefore,
2705 it must all be lexically valid C@.  Normally the only way this matters is
2706 that all comments and string literals inside a failing conditional group
2707 must still be properly ended.
2709 The comment following the @samp{#endif} is not required, but it is a
2710 good practice if there is a lot of @var{controlled text}, because it
2711 helps people match the @samp{#endif} to the corresponding @samp{#ifdef}.
2712 Older programs sometimes put @var{MACRO} directly after the
2713 @samp{#endif} without enclosing it in a comment.  This is invalid code
2714 according to the C standard.  GNU CPP accepts it with a warning.  It
2715 never affects which @samp{#ifndef} the @samp{#endif} matches.
2717 @findex #ifndef
2718 Sometimes you wish to use some code if a macro is @emph{not} defined.
2719 You can do this by writing @samp{#ifndef} instead of @samp{#ifdef}.
2720 One common use of @samp{#ifndef} is to include code only the first
2721 time a header file is included.  @xref{Once-Only Headers}.
2723 Macro definitions can vary between compilations for several reasons.
2724 Here are some samples.
2726 @itemize @bullet
2727 @item
2728 Some macros are predefined on each kind of machine
2729 (@pxref{System-specific Predefined Macros}).  This allows you to provide
2730 code specially tuned for a particular machine.
2732 @item
2733 System header files define more macros, associated with the features
2734 they implement.  You can test these macros with conditionals to avoid
2735 using a system feature on a machine where it is not implemented.
2737 @item
2738 Macros can be defined or undefined with the @option{-D} and @option{-U}
2739 command line options when you compile the program.  You can arrange to
2740 compile the same source file into two different programs by choosing a
2741 macro name to specify which program you want, writing conditionals to
2742 test whether or how this macro is defined, and then controlling the
2743 state of the macro with command line options, perhaps set in the
2744 Makefile.  @xref{Invocation}.
2746 @item
2747 Your program might have a special header file (often called
2748 @file{config.h}) that is adjusted when the program is compiled.  It can
2749 define or not define macros depending on the features of the system and
2750 the desired capabilities of the program.  The adjustment can be
2751 automated by a tool such as @command{autoconf}, or done by hand.
2752 @end itemize
2754 @node If
2755 @subsection If
2757 The @samp{#if} directive allows you to test the value of an arithmetic
2758 expression, rather than the mere existence of one macro.  Its syntax is
2760 @example
2761 @group
2762 #if @var{expression}
2764 @var{controlled text}
2766 #endif /* @var{expression} */
2767 @end group
2768 @end example
2770 @var{expression} is a C expression of integer type, subject to stringent
2771 restrictions.  It may contain
2773 @itemize @bullet
2774 @item
2775 Integer constants.
2777 @item
2778 Character constants, which are interpreted as they would be in normal
2779 code.
2781 @item
2782 Arithmetic operators for addition, subtraction, multiplication,
2783 division, bitwise operations, shifts, comparisons, and logical
2784 operations (@code{&&} and @code{||}).  The latter two obey the usual
2785 short-circuiting rules of standard C@.
2787 @item
2788 Macros.  All macros in the expression are expanded before actual
2789 computation of the expression's value begins.
2791 @item
2792 Uses of the @code{defined} operator, which lets you check whether macros
2793 are defined in the middle of an @samp{#if}.
2795 @item
2796 Identifiers that are not macros, which are all considered to be the
2797 number zero.  This allows you to write @code{@w{#if MACRO}} instead of
2798 @code{@w{#ifdef MACRO}}, if you know that MACRO, when defined, will
2799 always have a nonzero value.  Function-like macros used without their
2800 function call parentheses are also treated as zero.
2802 In some contexts this shortcut is undesirable.  The @option{-Wundef}
2803 option causes GCC to warn whenever it encounters an identifier which is
2804 not a macro in an @samp{#if}.
2805 @end itemize
2807 The preprocessor does not know anything about types in the language.
2808 Therefore, @code{sizeof} operators are not recognized in @samp{#if}, and
2809 neither are @code{enum} constants.  They will be taken as identifiers
2810 which are not macros, and replaced by zero.  In the case of
2811 @code{sizeof}, this is likely to cause the expression to be invalid.
2813 The preprocessor calculates the value of @var{expression}.  It carries
2814 out all calculations in the widest integer type known to the compiler;
2815 on most machines supported by GCC this is 64 bits.  This is not the same
2816 rule as the compiler uses to calculate the value of a constant
2817 expression, and may give different results in some cases.  If the value
2818 comes out to be nonzero, the @samp{#if} succeeds and the @var{controlled
2819 text} is included; otherwise it is skipped.
2821 If @var{expression} is not correctly formed, GCC issues an error and
2822 treats the conditional as having failed.
2824 @node Defined
2825 @subsection Defined
2827 @cindex @code{defined}
2828 The special operator @code{defined} is used in @samp{#if} and
2829 @samp{#elif} expressions to test whether a certain name is defined as a
2830 macro.  @code{defined @var{name}} and @code{defined (@var{name})} are
2831 both expressions whose value is 1 if @var{name} is defined as a macro at
2832 the current point in the program, and 0 otherwise.  Thus,  @code{@w{#if
2833 defined MACRO}} is precisely equivalent to @code{@w{#ifdef MACRO}}.
2835 @code{defined} is useful when you wish to test more than one macro for
2836 existence at once.  For example,
2838 @example
2839 #if defined (__vax__) || defined (__ns16000__)
2840 @end example
2842 @noindent
2843 would succeed if either of the names @code{__vax__} or
2844 @code{__ns16000__} is defined as a macro.
2846 Conditionals written like this:
2848 @example
2849 #if defined BUFSIZE && BUFSIZE >= 1024
2850 @end example
2852 @noindent
2853 can generally be simplified to just @code{@w{#if BUFSIZE >= 1024}},
2854 since if @code{BUFSIZE} is not defined, it will be interpreted as having
2855 the value zero.
2857 If the @code{defined} operator appears as a result of a macro expansion,
2858 the C standard says the behavior is undefined.  GNU cpp treats it as a
2859 genuine @code{defined} operator and evaluates it normally.  It will warn
2860 wherever your code uses this feature if you use the command-line option
2861 @option{-pedantic}, since other compilers may handle it differently.
2863 @node Else
2864 @subsection Else
2866 @findex #else
2867 The @samp{#else} directive can be added to a conditional to provide
2868 alternative text to be used if the condition fails.  This is what it
2869 looks like:
2871 @example
2872 @group
2873 #if @var{expression}
2874 @var{text-if-true}
2875 #else /* Not @var{expression} */
2876 @var{text-if-false}
2877 #endif /* Not @var{expression} */
2878 @end group
2879 @end example
2881 @noindent
2882 If @var{expression} is nonzero, the @var{text-if-true} is included and
2883 the @var{text-if-false} is skipped.  If @var{expression} is zero, the
2884 opposite happens.
2886 You can use @samp{#else} with @samp{#ifdef} and @samp{#ifndef}, too.
2888 @node Elif
2889 @subsection Elif
2891 @findex #elif
2892 One common case of nested conditionals is used to check for more than two
2893 possible alternatives.  For example, you might have
2895 @example
2896 #if X == 1
2897 @dots{}
2898 #else /* X != 1 */
2899 #if X == 2
2900 @dots{}
2901 #else /* X != 2 */
2902 @dots{}
2903 #endif /* X != 2 */
2904 #endif /* X != 1 */
2905 @end example
2907 Another conditional directive, @samp{#elif}, allows this to be
2908 abbreviated as follows:
2910 @example
2911 #if X == 1
2912 @dots{}
2913 #elif X == 2
2914 @dots{}
2915 #else /* X != 2 and X != 1*/
2916 @dots{}
2917 #endif /* X != 2 and X != 1*/
2918 @end example
2920 @samp{#elif} stands for ``else if''.  Like @samp{#else}, it goes in the
2921 middle of a conditional group and subdivides it; it does not require a
2922 matching @samp{#endif} of its own.  Like @samp{#if}, the @samp{#elif}
2923 directive includes an expression to be tested.  The text following the
2924 @samp{#elif} is processed only if the original @samp{#if}-condition
2925 failed and the @samp{#elif} condition succeeds.
2927 More than one @samp{#elif} can go in the same conditional group.  Then
2928 the text after each @samp{#elif} is processed only if the @samp{#elif}
2929 condition succeeds after the original @samp{#if} and all previous
2930 @samp{#elif} directives within it have failed.
2932 @samp{#else} is allowed after any number of @samp{#elif} directives, but
2933 @samp{#elif} may not follow @samp{#else}.
2935 @node Deleted Code
2936 @section Deleted Code
2937 @cindex commenting out code
2939 If you replace or delete a part of the program but want to keep the old
2940 code around for future reference, you often cannot simply comment it
2941 out.  Block comments do not nest, so the first comment inside the old
2942 code will end the commenting-out.  The probable result is a flood of
2943 syntax errors.
2945 One way to avoid this problem is to use an always-false conditional
2946 instead.  For instance, put @code{#if 0} before the deleted code and
2947 @code{#endif} after it.  This works even if the code being turned
2948 off contains conditionals, but they must be entire conditionals
2949 (balanced @samp{#if} and @samp{#endif}).
2951 Some people use @code{#ifdef notdef} instead.  This is risky, because
2952 @code{notdef} might be accidentally defined as a macro, and then the
2953 conditional would succeed.  @code{#if 0} can be counted on to fail.
2955 Do not use @code{#if 0} for comments which are not C code.  Use a real
2956 comment, instead.  The interior of @code{#if 0} must consist of complete
2957 tokens; in particular, single-quote characters must balance.  Comments
2958 often contain unbalanced single-quote characters (known in English as
2959 apostrophes).  These confuse @code{#if 0}.  They don't confuse
2960 @samp{/*}.
2962 @node Diagnostics
2963 @chapter Diagnostics
2964 @cindex diagnostic
2965 @cindex reporting errors
2966 @cindex reporting warnings
2968 @findex #error
2969 The directive @samp{#error} causes the preprocessor to report a fatal
2970 error.  The tokens forming the rest of the line following @samp{#error}
2971 are used as the error message.
2973 You would use @samp{#error} inside of a conditional that detects a
2974 combination of parameters which you know the program does not properly
2975 support.  For example, if you know that the program will not run
2976 properly on a VAX, you might write
2978 @example
2979 @group
2980 #ifdef __vax__
2981 #error "Won't work on VAXen.  See comments at get_last_object."
2982 #endif
2983 @end group
2984 @end example
2986 If you have several configuration parameters that must be set up by
2987 the installation in a consistent way, you can use conditionals to detect
2988 an inconsistency and report it with @samp{#error}.  For example,
2990 @example
2991 #if !defined(UNALIGNED_INT_ASM_OP) && defined(DWARF2_DEBUGGING_INFO)
2992 #error "DWARF2_DEBUGGING_INFO requires UNALIGNED_INT_ASM_OP."
2993 #endif
2994 @end example
2996 @findex #warning
2997 The directive @samp{#warning} is like @samp{#error}, but causes the
2998 preprocessor to issue a warning and continue preprocessing.  The tokens
2999 following @samp{#warning} are used as the warning message.
3001 You might use @samp{#warning} in obsolete header files, with a message
3002 directing the user to the header file which should be used instead.
3004 Neither @samp{#error} nor @samp{#warning} macro-expands its argument.
3005 Internal whitespace sequences are each replaced with a single space.
3006 The line must consist of complete tokens.  It is wisest to make the
3007 argument of these directives be a single string constant; this avoids
3008 problems with apostrophes and the like.
3010 @node Line Control
3011 @chapter Line Control
3012 @cindex line control
3014 The C preprocessor informs the C compiler of the location in your source
3015 code where each token came from.  Presently, this is just the file name
3016 and line number.  All the tokens resulting from macro expansion are
3017 reported as having appeared on the line of the source file where the
3018 outermost macro was used.  We intend to be more accurate in the future.
3020 If you write a program which generates source code, such as the
3021 @command{bison} parser generator, you may want to adjust the preprocessor's
3022 notion of the current file name and line number by hand.  Parts of the
3023 output from @command{bison} are generated from scratch, other parts come
3024 from a standard parser file.  The rest are copied verbatim from
3025 @command{bison}'s input.  You would like compiler error messages and
3026 symbolic debuggers to be able to refer to @code{bison}'s input file.
3028 @findex #line
3029 @command{bison} or any such program can arrange this by writing
3030 @samp{#line} directives into the output file.  @samp{#line} is a
3031 directive that specifies the original line number and source file name
3032 for subsequent input in the current preprocessor input file.
3033 @samp{#line} has three variants:
3035 @table @code
3036 @item #line @var{linenum}
3037 @var{linenum} is a non-negative decimal integer constant.  It specifies
3038 the line number which should be reported for the following line of
3039 input.  Subsequent lines are counted from @var{linenum}.
3041 @item #line @var{linenum} @var{filename}
3042 @var{linenum} is the same as for the first form, and has the same
3043 effect.  In addition, @var{filename} is a string constant.  The
3044 following line and all subsequent lines are reported to come from the
3045 file it specifies, until something else happens to change that.
3046 @var{filename} is interpreted according to the normal rules for a string
3047 constant: backslash escapes are interpreted.  This is different from
3048 @samp{#include}.
3050 Previous versions of GNU CPP did not interpret escapes in @samp{#line};
3051 we have changed it because the standard requires they be interpreted,
3052 and most other compilers do.
3054 @item #line @var{anything else}
3055 @var{anything else} is checked for macro calls, which are expanded.
3056 The result should match one of the above two forms.
3057 @end table
3059 @samp{#line} directives alter the results of the @code{__FILE__} and
3060 @code{__LINE__} predefined macros from that point on.  @xref{Standard
3061 Predefined Macros}.  They do not have any effect on @samp{#include}'s
3062 idea of the directory containing the current file.  This is a change
3063 from GCC 2.95.  Previously, a file reading
3065 @smallexample
3066 #line 1 "../src/gram.y"
3067 #include "gram.h"
3068 @end smallexample
3070 would search for @file{gram.h} in @file{../src}, then the @option{-I}
3071 chain; the directory containing the physical source file would not be
3072 searched.  In GCC 3.0 and later, the @samp{#include} is not affected by
3073 the presence of a @samp{#line} referring to a different directory.
3075 We made this change because the old behavior caused problems when
3076 generated source files were transported between machines.  For instance,
3077 it is common practice to ship generated parsers with a source release,
3078 so that people building the distribution do not need to have yacc or
3079 Bison installed.  These files frequently have @samp{#line} directives
3080 referring to the directory tree of the system where the distribution was
3081 created.  If GCC tries to search for headers in those directories, the
3082 build is likely to fail.
3084 The new behavior can cause failures too, if the generated file is not
3085 in the same directory as its source and it attempts to include a header
3086 which would be visible searching from the directory containing the
3087 source file.  However, this problem is easily solved with an additional
3088 @option{-I} switch on the command line.  The failures caused by the old
3089 semantics could sometimes be corrected only by editing the generated
3090 files, which is difficult and error-prone.
3092 @node Pragmas
3093 @chapter Pragmas
3095 The @samp{#pragma} directive is the method specified by the C standard
3096 for providing additional information to the compiler, beyond what is
3097 conveyed in the language itself.  Three forms of this directive
3098 (commonly known as @dfn{pragmas}) are specified by the 1999 C standard.
3099 A C compiler is free to attach any meaning it likes to other pragmas.
3101 GCC has historically preferred to use extensions to the syntax of the
3102 language, such as @code{__attribute__}, for this purpose.  However, GCC
3103 does define a few pragmas of its own.  These mostly have effects on the
3104 entire translation unit or source file.
3106 In GCC version 3, all GNU-defined, supported pragmas have been given a
3107 @code{GCC} prefix.  This is in line with the @code{STDC} prefix on all
3108 pragmas defined by C99.  For backward compatibility, pragmas which were
3109 recognized by previous versions are still recognized without the
3110 @code{GCC} prefix, but that usage is deprecated.  Some older pragmas are
3111 deprecated in their entirety.  They are not recognized with the
3112 @code{GCC} prefix.  @xref{Obsolete Features}.
3114 @cindex @code{_Pragma}
3115 C99 introduces the @code{@w{_Pragma}} operator.  This feature addresses a
3116 major problem with @samp{#pragma}: being a directive, it cannot be
3117 produced as the result of macro expansion.  @code{@w{_Pragma}} is an
3118 operator, much like @code{sizeof} or @code{defined}, and can be embedded
3119 in a macro.
3121 Its syntax is @code{@w{_Pragma (@var{string-literal})}}, where
3122 @var{string-literal} can be either a normal or wide-character string
3123 literal.  It is destringized, by replacing all @samp{\\} with a single
3124 @samp{\} and all @samp{\"} with a @samp{"}.  The result is then
3125 processed as if it had appeared as the right hand side of a
3126 @samp{#pragma} directive.  For example,
3128 @example
3129 _Pragma ("GCC dependency \"parse.y\"")
3130 @end example
3132 @noindent
3133 has the same effect as @code{#pragma GCC dependency "parse.y"}.  The
3134 same effect could be achieved using macros, for example
3136 @example
3137 #define DO_PRAGMA(x) _Pragma (#x)
3138 DO_PRAGMA (GCC dependency "parse.y")
3139 @end example
3141 The standard is unclear on where a @code{_Pragma} operator can appear.
3142 The preprocessor does not accept it within a preprocessing conditional
3143 directive like @samp{#if}.  To be safe, you are probably best keeping it
3144 out of directives other than @samp{#define}, and putting it on a line of
3145 its own.
3147 This manual documents the pragmas which are meaningful to the
3148 preprocessor itself.  Other pragmas are meaningful to the C or C++
3149 compilers.  They are documented in the GCC manual.
3151 @ftable @code
3152 @item #pragma GCC dependency
3153 @code{#pragma GCC dependency} allows you to check the relative dates of
3154 the current file and another file.  If the other file is more recent than
3155 the current file, a warning is issued.  This is useful if the current
3156 file is derived from the other file, and should be regenerated.  The
3157 other file is searched for using the normal include search path.
3158 Optional trailing text can be used to give more information in the
3159 warning message.
3161 @example
3162 #pragma GCC dependency "parse.y"
3163 #pragma GCC dependency "/usr/include/time.h" rerun fixincludes
3164 @end example
3166 @item #pragma GCC poison
3167 Sometimes, there is an identifier that you want to remove completely
3168 from your program, and make sure that it never creeps back in.  To
3169 enforce this, you can @dfn{poison} the identifier with this pragma.
3170 @code{#pragma GCC poison} is followed by a list of identifiers to
3171 poison.  If any of those identifiers appears anywhere in the source
3172 after the directive, it is a hard error.  For example,
3174 @example
3175 #pragma GCC poison printf sprintf fprintf
3176 sprintf(some_string, "hello");
3177 @end example
3179 @noindent
3180 will produce an error.
3182 If a poisoned identifier appears as part of the expansion of a macro
3183 which was defined before the identifier was poisoned, it will @emph{not}
3184 cause an error.  This lets you poison an identifier without worrying
3185 about system headers defining macros that use it.
3187 For example,
3189 @example
3190 #define strrchr rindex
3191 #pragma GCC poison rindex
3192 strrchr(some_string, 'h');
3193 @end example
3195 @noindent
3196 will not produce an error.
3198 @item #pragma GCC system_header
3199 This pragma takes no arguments.  It causes the rest of the code in the
3200 current file to be treated as if it came from a system header.
3201 @xref{System Headers}.
3203 @end ftable
3205 @node Other Directives
3206 @chapter Other Directives
3208 @findex #ident
3209 The @samp{#ident} directive takes one argument, a string constant.  On
3210 some systems, that string constant is copied into a special segment of
3211 the object file.  On other systems, the directive is ignored.
3213 This directive is not part of the C standard, but it is not an official
3214 GNU extension either.  We believe it came from System V@.
3216 @findex #sccs
3217 The @samp{#sccs} directive is recognized on some systems, because it
3218 appears in their header files.  It is a very old, obscure, extension
3219 which we did not invent, and we have been unable to find any
3220 documentation of what it should do, so GCC simply ignores it.
3222 @cindex null directive
3223 The @dfn{null directive} consists of a @samp{#} followed by a newline,
3224 with only whitespace (including comments) in between.  A null directive
3225 is understood as a preprocessing directive but has no effect on the
3226 preprocessor output.  The primary significance of the existence of the
3227 null directive is that an input line consisting of just a @samp{#} will
3228 produce no output, rather than a line of output containing just a
3229 @samp{#}.  Supposedly some old C programs contain such lines.
3231 @node Preprocessor Output
3232 @chapter Preprocessor Output
3234 When the C preprocessor is used with the C, C++, or Objective-C
3235 compilers, it is integrated into the compiler and communicates a stream
3236 of binary tokens directly to the compiler's parser.  However, it can
3237 also be used in the more conventional standalone mode, where it produces
3238 textual output.
3239 @c FIXME: Document the library interface.
3241 @cindex output format
3242 The output from the C preprocessor looks much like the input, except
3243 that all preprocessing directive lines have been replaced with blank
3244 lines and all comments with spaces.  Long runs of blank lines are
3245 discarded.
3247 The ISO standard specifies that it is implementation defined whether a
3248 preprocessor preserves whitespace between tokens, or replaces it with
3249 e.g.@: a single space.  In GNU CPP, whitespace between tokens is collapsed
3250 to become a single space, with the exception that the first token on a
3251 non-directive line is preceded with sufficient spaces that it appears in
3252 the same column in the preprocessed output that it appeared in the
3253 original source file.  This is so the output is easy to read.
3254 @xref{Differences from previous versions}.  CPP does not insert any
3255 whitespace where there was none in the original source, except where
3256 necessary to prevent an accidental token paste.
3258 @cindex linemarkers
3259 Source file name and line number information is conveyed by lines
3260 of the form
3262 @example
3263 # @var{linenum} @var{filename} @var{flags}
3264 @end example
3266 @noindent
3267 These are called @dfn{linemarkers}.  They are inserted as needed into
3268 the output (but never within a string or character constant).  They mean
3269 that the following line originated in file @var{filename} at line
3270 @var{linenum}.  @var{filename} will never contain any non-printing
3271 characters; they are replaced with octal escape sequences.
3273 After the file name comes zero or more flags, which are @samp{1},
3274 @samp{2}, @samp{3}, or @samp{4}.  If there are multiple flags, spaces
3275 separate them.  Here is what the flags mean:
3277 @table @samp
3278 @item 1
3279 This indicates the start of a new file.
3280 @item 2
3281 This indicates returning to a file (after having included another file).
3282 @item 3
3283 This indicates that the following text comes from a system header file,
3284 so certain warnings should be suppressed.
3285 @item 4
3286 This indicates that the following text should be treated as being
3287 wrapped in an implicit @code{extern "C"} block.
3288 @c maybe cross reference NO_IMPLICIT_EXTERN_C
3289 @end table
3291 As an extension, the preprocessor accepts linemarkers in non-assembler
3292 input files.  They are treated like the corresponding @samp{#line}
3293 directive, (@pxref{Line Control}), except that trailing flags are
3294 permitted, and are interpreted with the meanings described above.  If
3295 multiple flags are given, they must be in ascending order.
3297 Some directives may be duplicated in the output of the preprocessor.
3298 These are @samp{#ident} (always), @samp{#pragma} (only if the
3299 preprocessor does not handle the pragma itself), and @samp{#define} and
3300 @samp{#undef} (with certain debugging options).  If this happens, the
3301 @samp{#} of the directive will always be in the first column, and there
3302 will be no space between the @samp{#} and the directive name.  If macro
3303 expansion happens to generate tokens which might be mistaken for a
3304 duplicated directive, a space will be inserted between the @samp{#} and
3305 the directive name.
3307 @node Traditional Mode
3308 @chapter Traditional Mode
3310 Traditional (pre-standard) C preprocessing is rather different from
3311 the preprocessing specified by the standard.  When GCC is given the
3312 @option{-traditional} option, it attempts to emulate a traditional
3313 preprocessor.  We do not guarantee that GCC's behavior under
3314 @option{-traditional} matches any pre-standard preprocessor exactly.
3316 Traditional mode exists only for backward compatibility.  We have no
3317 plans to augment it in any way nor will we change it except to fix
3318 catastrophic bugs.  You should be aware that modern C libraries often
3319 have header files which are incompatible with traditional mode.
3321 This is a list of the differences.  It may not be complete, and may not
3322 correspond exactly to the behavior of either GCC or a true traditional
3323 preprocessor.
3325 @itemize @bullet
3326 @item
3327 Traditional macro expansion pays no attention to single-quote or
3328 double-quote characters; macro argument symbols are replaced by the
3329 argument values even when they appear within apparent string or
3330 character constants.
3332 @item
3333 Traditionally, it is permissible for a macro expansion to end in the
3334 middle of a string or character constant.  The constant continues into
3335 the text surrounding the macro call.
3337 @item
3338 However, the end of the line terminates a string or character constant,
3339 with no error.  (This is a kluge.  Traditional mode is commonly used to
3340 preprocess things which are not C, and have a different comment syntax.
3341 Single apostrophes often appear in comments.  This kluge prevents the
3342 traditional preprocessor from issuing errors on such comments.)
3344 @item
3345 Preprocessing directives are recognized in traditional C only when their
3346 leading @samp{#} appears in the first column.  There can be no
3347 whitespace between the beginning of the line and the @samp{#}.
3349 @item
3350 In traditional C, a comment is equivalent to no text at all.  (In ISO
3351 C, a comment counts as whitespace.)  It can be used sort of the same way
3352 that @samp{##} is used in ISO C, to paste macro arguments together.
3354 @item
3355 Traditional C does not have the concept of a preprocessing number.
3357 @item
3358 A macro is not suppressed within its own definition, in traditional C@.
3359 Thus, any macro that is used recursively inevitably causes an error.
3361 @item
3362 The @samp{#} and @samp{##} operators are not available in traditional
3365 @item
3366 In traditional C, the text at the end of a macro expansion can run
3367 together with the text after the macro call, to produce a single token.
3368 This is impossible in ISO C@.
3370 @item
3371 None of the GNU extensions to the preprocessor are available in
3372 traditional mode, with the exception of a partial implementation of
3373 assertions, and those may be removed in the future.
3375 @item
3376 A true traditional C preprocessor does not recognize @samp{#elif},
3377 @samp{#error}, or @samp{#pragma}.  GCC supports @samp{#elif} and
3378 @samp{#error} even in traditional mode, but not @samp{#pragma}.
3380 @item
3381 Traditional mode is text-based, not token-based, and comments are
3382 stripped after macro expansion.  Therefore, @samp{/**/} can be used to
3383 paste tokens together provided that there is no whitespace between it
3384 and the tokens to be pasted.
3386 @item
3387 Traditional mode preserves the amount and form of whitespace provided by
3388 the user.  Hard tabs remain hard tabs.  This can be useful, e.g.@: if you
3389 are preprocessing a Makefile (which we do not encourage).
3390 @end itemize
3392 You can request warnings about features that did not exist, or worked
3393 differently, in traditional C with the @option{-Wtraditional} option.
3394 This works only if you do @emph{not} specify @option{-traditional}.  GCC
3395 does not warn about features of ISO C which you must use when you are
3396 using a conforming compiler, such as the @samp{#} and @samp{##}
3397 operators.
3399 Presently @option{-Wtraditional} warns about:
3401 @itemize @bullet
3402 @item
3403 Macro parameters that appear within string literals in the macro body.
3404 In traditional C macro replacement takes place within string literals,
3405 but does not in ISO C@.
3407 @item
3408 In traditional C, some preprocessor directives did not exist.
3409 Traditional preprocessors would only consider a line to be a directive
3410 if the @samp{#} appeared in column 1 on the line.  Therefore
3411 @option{-Wtraditional} warns about directives that traditional C
3412 understands but would ignore because the @samp{#} does not appear as the
3413 first character on the line.  It also suggests you hide directives like
3414 @samp{#pragma} not understood by traditional C by indenting them.  Some
3415 traditional implementations would not recognize @samp{#elif}, so it
3416 suggests avoiding it altogether.
3418 @item
3419 A function-like macro that appears without an argument list.  In
3420 traditional C this was an error.  In ISO C it merely means that the
3421 macro is not expanded.
3423 @item
3424 The unary plus operator.  This did not exist in traditional C@.
3426 @item
3427 The @samp{U} and @samp{LL} integer constant suffixes, which were not
3428 available in traditional C@.  (Traditional C does support the @samp{L}
3429 suffix for simple long integer constants.)  You are not warned about
3430 uses of these suffixes in macros defined in system headers.  For
3431 instance, @code{UINT_MAX} may well be defined as @code{4294967295U}, but
3432 you will not be warned if you use @code{UINT_MAX}.
3434 You can usually avoid the warning, and the related warning about
3435 constants which are so large that they are unsigned, by writing the
3436 integer constant in question in hexadecimal, with no U suffix.  Take
3437 care, though, because this gives the wrong result in exotic cases.
3438 @end itemize
3440 @node Implementation Details
3441 @chapter Implementation Details
3443 Here we document details of how the preprocessor's implementation
3444 affects its user-visible behavior.  You should try to avoid undue
3445 reliance on behavior described here, as it is possible that it will
3446 change subtly in future implementations.
3448 Also documented here are obsolete features and changes from previous
3449 versions of GNU CPP@.
3451 @menu
3452 * Implementation-defined behavior::
3453 * Implementation limits::
3454 * Obsolete Features::
3455 * Differences from previous versions::
3456 @end menu
3458 @node Implementation-defined behavior
3459 @section Implementation-defined behavior
3460 @cindex implementation-defined behavior
3462 This is how GNU CPP behaves in all the cases which the C standard
3463 describes as @dfn{implementation-defined}.  This term means that the
3464 implementation is free to do what it likes, but must document its choice
3465 and stick to it.
3466 @c FIXME: Check the C++ standard for more implementation-defined stuff.
3468 @itemize @bullet
3469 @need 1000
3470 @item The mapping of physical source file multi-byte characters to the
3471 execution character set.
3473 Currently, GNU cpp only supports character sets that are strict supersets
3474 of ASCII, and performs no translation of characters.
3476 @item Non-empty sequences of whitespace characters.
3478 In textual output, each whitespace sequence is collapsed to a single
3479 space.  For aesthetic reasons, the first token on each non-directive
3480 line of output is preceded with sufficient spaces that it appears in the
3481 same column as it did in the original source file.
3483 @item The numeric value of character constants in preprocessor expressions.
3485 The preprocessor and compiler interpret character constants in the same
3486 way; escape sequences such as @samp{\a} are given the values they would
3487 have on the target machine.
3489 Multi-character character constants are interpreted a character at a
3490 time, shifting the previous result left by the number of bits per
3491 character on the host, and adding the new character.  For example, 'ab'
3492 on an 8-bit host would be interpreted as @w{'a' * 256 + 'b'}.  If there
3493 are more characters in the constant than can fit in the widest native
3494 integer type on the host, usually a @code{long}, the excess characters
3495 are ignored and a diagnostic is given.
3497 @item Source file inclusion.
3499 For a discussion on how the preprocessor locates header files,
3500 @ref{Include Operation}.
3502 @item Interpretation of the filename resulting from a macro-expanded
3503 @samp{#include} directive.
3505 @xref{Computed Includes}.
3507 @item Treatment of a @samp{#pragma} directive that after macro-expansion
3508 results in a standard pragma.
3510 No macro expansion occurs on any @samp{#pragma} directive line, so the
3511 question does not arise.
3513 Note that GCC does not yet implement any of the standard
3514 pragmas.
3516 @end itemize
3518 @node Implementation limits
3519 @section Implementation limits
3520 @cindex implementation limits
3522 GNU CPP has a small number of internal limits.  This section lists the
3523 limits which the C standard requires to be no lower than some minimum,
3524 and all the others we are aware of.  We intend there to be as few limits
3525 as possible.  If you encounter an undocumented or inconvenient limit,
3526 please report that to us as a bug.  (See the section on reporting bugs in
3527 the GCC manual.)
3529 Where we say something is limited @dfn{only by available memory}, that
3530 means that internal data structures impose no intrinsic limit, and space
3531 is allocated with @code{malloc} or equivalent.  The actual limit will
3532 therefore depend on many things, such as the size of other things
3533 allocated by the compiler at the same time, the amount of memory
3534 consumed by other processes on the same computer, etc.
3536 @itemize @bullet
3538 @item Nesting levels of @samp{#include} files.
3540 We impose an arbitrary limit of 200 levels, to avoid runaway recursion.
3541 The standard requires at least 15 levels.
3543 @item Nesting levels of conditional inclusion.
3545 The C standard mandates this be at least 63.  GNU CPP is limited only by
3546 available memory.
3548 @item Levels of parenthesised expressions within a full expression.
3550 The C standard requires this to be at least 63.  In preprocessor
3551 conditional expressions, it is limited only by available memory.
3553 @item Significant initial characters in an identifier or macro name.
3555 The preprocessor treats all characters as significant.  The C standard
3556 requires only that the first 63 be significant.
3558 @item Number of macros simultaneously defined in a single translation unit.
3560 The standard requires at least 4095 be possible.  GNU CPP is limited only
3561 by available memory.
3563 @item Number of parameters in a macro definition and arguments in a macro call.
3565 We allow @code{USHRT_MAX}, which is no smaller than 65,535.  The minimum
3566 required by the standard is 127.
3568 @item Number of characters on a logical source line.
3570 The C standard requires a minimum of 4096 be permitted.  GNU CPP places
3571 no limits on this, but you may get incorrect column numbers reported in
3572 diagnostics for lines longer than 65,535 characters.
3574 @item Maximum size of a source file.
3576 The standard does not specify any lower limit on the maximum size of a
3577 source file.  GNU cpp maps files into memory, so it is limited by the
3578 available address space.  This is generally at least two gigabytes.
3579 Depending on the operating system, the size of physical memory may or
3580 may not be a limitation.
3582 @end itemize
3584 @node Obsolete Features
3585 @section Obsolete Features
3587 GNU CPP has a number of features which are present mainly for
3588 compatibility with older programs.  We discourage their use in new code.
3589 In some cases, we plan to remove the feature in a future version of GCC@.
3591 @menu
3592 * Assertions::
3593 * Obsolete once-only headers::
3594 * Miscellaneous obsolete features::
3595 @end menu
3597 @node Assertions
3598 @subsection Assertions
3599 @cindex assertions
3601 @dfn{Assertions} are a deprecated alternative to macros in writing
3602 conditionals to test what sort of computer or system the compiled
3603 program will run on.  Assertions are usually predefined, but you can
3604 define them with preprocessing directives or command-line options.
3606 Assertions were intended to provide a more systematic way to describe
3607 the compiler's target system.  However, in practice they are just as
3608 unpredictable as the system-specific predefined macros.  In addition, they
3609 are not part of any standard, and only a few compilers support them.
3610 Therefore, the use of assertions is @strong{less} portable than the use
3611 of system-specific predefined macros.  We recommend you do not use them at
3612 all.
3614 @cindex predicates
3615 An assertion looks like this:
3617 @example
3618 #@var{predicate} (@var{answer})
3619 @end example
3621 @noindent
3622 @var{predicate} must be a single identifier.  @var{answer} can be any
3623 sequence of tokens; all characters are significant except for leading
3624 and trailing whitespace, and differences in internal whitespace
3625 sequences are ignored.  (This is similar to the rules governing macro
3626 redefinition.)  Thus, @code{(x + y)} is different from @code{(x+y)} but
3627 equivalent to @code{@w{( x + y )}}.  Parentheses do not nest inside an
3628 answer.
3630 @cindex testing predicates
3631 To test an assertion, you write it in an @samp{#if}.  For example, this
3632 conditional succeeds if either @code{vax} or @code{ns16000} has been
3633 asserted as an answer for @code{machine}.
3635 @example
3636 #if #machine (vax) || #machine (ns16000)
3637 @end example
3639 @noindent
3640 You can test whether @emph{any} answer is asserted for a predicate by
3641 omitting the answer in the conditional:
3643 @example
3644 #if #machine
3645 @end example
3647 @findex #assert
3648 Assertions are made with the @samp{#assert} directive.  Its sole
3649 argument is the assertion to make, without the leading @samp{#} that
3650 identifies assertions in conditionals.
3652 @example
3653 #assert @var{predicate} (@var{answer})
3654 @end example
3656 @noindent
3657 You may make several assertions with the same predicate and different
3658 answers.  Subsequent assertions do not override previous ones for the
3659 same predicate.  All the answers for any given predicate are
3660 simultaneously true.
3662 @cindex assertions, cancelling
3663 @findex #unassert
3664 Assertions can be cancelled with the @samp{#unassert} directive.  It
3665 has the same syntax as @samp{#assert}.  In that form it cancels only the
3666 answer which was specified on the @samp{#unassert} line; other answers
3667 for that predicate remain true.  You can cancel an entire predicate by
3668 leaving out the answer:
3670 @example
3671 #unassert @var{predicate}
3672 @end example
3674 @noindent
3675 In either form, if no such assertion has been made, @samp{#unassert} has
3676 no effect.
3678 You can also make or cancel assertions using command line options.
3679 @xref{Invocation}.
3681 @node Obsolete once-only headers
3682 @subsection Obsolete once-only headers
3684 GNU CPP supports two more ways of indicating that a header file should be
3685 read only once.  Neither one is as portable as a wrapper @samp{#ifndef},
3686 and we recommend you do not use them in new programs.
3688 @findex #import
3689 In the Objective-C language, there is a variant of @samp{#include}
3690 called @samp{#import} which includes a file, but does so at most once.
3691 If you use @samp{#import} instead of @samp{#include}, then you don't
3692 need the conditionals inside the header file to prevent multiple
3693 inclusion of the contents.  GCC permits the use of @samp{#import} in C
3694 and C++ as well as Objective-C@.  However, it is not in standard C or C++
3695 and should therefore not be used by portable programs.
3697 @samp{#import} is not a well designed feature.  It requires the users of
3698 a header file to know that it should only be included once.  It is much
3699 better for the header file's implementor to write the file so that users
3700 don't need to know this.  Using a wrapper @samp{#ifndef} accomplishes
3701 this goal.
3703 In the present implementation, a single use of @samp{#import} will
3704 prevent the file from ever being read again, by either @samp{#import} or
3705 @samp{#include}.  You should not rely on this; do not use both
3706 @samp{#import} and @samp{#include} to refer to the same header file.
3708 Another way to prevent a header file from being included more than once
3709 is with the @samp{#pragma once} directive.  If @samp{#pragma once} is
3710 seen when scanning a header file, that file will never be read again, no
3711 matter what.
3713 @samp{#pragma once} does not have the problems that @samp{#import} does,
3714 but it is not recognized by all preprocessors, so you cannot rely on it
3715 in a portable program.
3717 @node Miscellaneous obsolete features
3718 @subsection Miscellaneous obsolete features
3720 Here are a few more obsolete features.
3722 @itemize @bullet
3723 @cindex invalid token paste
3724 @item Attempting to paste two tokens which together do not form a valid
3725 preprocessing token.
3727 The preprocessor currently warns about this and outputs the two tokens
3728 adjacently, which is probably the behavior the programmer intends.  It
3729 may not work in future, though.
3731 Most of the time, when you get this warning, you will find that @samp{##}
3732 is being used superstitiously, to guard against whitespace appearing
3733 between two tokens.  It is almost always safe to delete the @samp{##}.
3735 @cindex pragma poison
3736 @item @code{#pragma poison}
3738 This is the same as @code{#pragma GCC poison}.  The version without the
3739 @code{GCC} prefix is deprecated.  @xref{Pragmas}.
3741 @cindex multi-line string constants
3742 @item Multi-line string constants
3744 GCC currently allows a string constant to extend across multiple logical
3745 lines of the source file.  This extension is deprecated and will be
3746 removed in a future version of GCC@.  Such string constants are already
3747 rejected in all directives apart from @samp{#define}.
3749 Instead, make use of ISO C concatenation of adjacent string literals, or
3750 use @samp{\n} followed by a backslash-newline.
3752 @end itemize
3754 @node Differences from previous versions
3755 @section Differences from previous versions
3756 @cindex differences from previous versions
3758 This section details behavior which has changed from previous versions
3759 of GNU CPP@.  We do not plan to change it again in the near future, but
3760 we do not promise not to, either.
3762 The ``previous versions'' discussed here are 2.95 and before.  The
3763 behavior of GCC 3.0 is mostly the same as the behavior of the widely
3764 used 2.96 and 2.97 development snapshots.  Where there are differences,
3765 they generally represent bugs in the snapshots.
3767 @itemize @bullet
3769 @item Order of evaluation of @samp{#} and @samp{##} operators
3771 The standard does not specify the order of evaluation of a chain of
3772 @samp{##} operators, nor whether @samp{#} is evaluated before, after, or
3773 at the same time as @samp{##}.  You should therefore not write any code
3774 which depends on any specific ordering.  It is possible to guarantee an
3775 ordering, if you need one, by suitable use of nested macros.
3777 An example of where this might matter is pasting the arguments @samp{1},
3778 @samp{e} and @samp{-2}.  This would be fine for left-to-right pasting,
3779 but right-to-left pasting would produce an invalid token @samp{e-2}.
3781 GCC 3.0 evaluates @samp{#} and @samp{##} at the same time and strictly
3782 left to right.  Older versions evaluated all @samp{#} operators first,
3783 then all @samp{##} operators, in an unreliable order.
3785 @item The form of whitespace betwen tokens in preprocessor output
3787 @xref{Preprocessor Output}, for the current textual format.  This is
3788 also the format used by stringification.  Normally, the preprocessor
3789 communicates tokens directly to the compiler's parser, and whitespace
3790 does not come up at all.
3792 Older versions of GCC preserved all whitespace provided by the user and
3793 inserted lots more whitespace of their own, because they could not
3794 accurately predict when extra spaces were needed to prevent accidental
3795 token pasting.
3797 @item Optional argument when invoking rest argument macros
3799 As an extension, GCC permits you to omit the variable arguments entirely
3800 when you use a variable argument macro.  This is forbidden by the 1999 C
3801 standard, and will provoke a pedantic warning with GCC 3.0.  Previous
3802 versions accepted it silently.
3804 @item @samp{##} swallowing preceding text in rest argument macros
3806 Formerly, in a macro expansion, if @samp{##} appeared before a variable
3807 arguments parameter, and the set of tokens specified for that argument
3808 in the macro invocation was empty, previous versions of GNU CPP would
3809 back up and remove the preceding sequence of non-whitespace characters
3810 (@strong{not} the preceding token).  This extension is in direct
3811 conflict with the 1999 C standard and has been drastically pared back.
3813 In the current version of the preprocessor, if @samp{##} appears between
3814 a comma and a variable arguments parameter, and the variable argument is
3815 omitted entirely, the comma will be removed from the expansion.  If the
3816 variable argument is empty, or the token before @samp{##} is not a
3817 comma, then @samp{##} behaves as a normal token paste.
3819 @item Traditional mode and GNU extensions
3821 Traditional mode used to be implemented in the same program as normal
3822 preprocessing.  Therefore, all the GNU extensions to the preprocessor
3823 were still available in traditional mode.  It is now a separate program
3824 and does not implement any of the GNU extensions, except for a partial
3825 implementation of assertions.  Even those may be removed in a future
3826 release.
3828 @item @samp{#line} and @samp{#include}
3830 The @samp{#line} directive used to change GCC's notion of the
3831 ``directory containing the current file,'' used by @samp{#include} with
3832 a double-quoted header file name.  In 3.0 and later, it does not.
3833 @xref{Line Control}, for further explanation.
3835 @item Syntax of @samp{#line}
3837 In GCC 2.95 and previous, the string constant argument to @samp{#line}
3838 was treated the same way as the argument to @samp{#include}: backslash
3839 escapes were not honored, and the string ended at the second @samp{"}.
3840 This is not compliant with the C standard.  In GCC 3.0, an attempt was
3841 made to correct the behavior, so that the string was treated as a real
3842 string constant, but it turned out to be buggy.  In 3.1, the bugs have
3843 been fixed.  (We are not fixing the bugs in 3.0 because they affect
3844 relatively few people and the fix is quite invasive.)
3846 @end itemize
3848 @node Invocation
3849 @chapter Invocation
3850 @cindex invocation
3851 @cindex command line
3853 Most often when you use the C preprocessor you will not have to invoke it
3854 explicitly: the C compiler will do so automatically.  However, the
3855 preprocessor is sometimes useful on its own.  All the options listed
3856 here are also acceptable to the C compiler and have the same meaning,
3857 except that the C compiler has different rules for specifying the output
3858 file.
3860 @strong{Note:} Whether you use the preprocessor by way of @command{gcc}
3861 or @command{cpp}, the @dfn{compiler driver} is run first.  This
3862 program's purpose is to translate your command into invocations of the
3863 programs that do the actual work.  Their command line interfaces are
3864 similar but not identical to the documented interface, and may change
3865 without notice.
3867 @ignore
3868 @c man begin SYNOPSIS
3869 cpp [@option{-D}@var{macro}[=@var{defn}]@dots{}] [@option{-U}@var{macro}]
3870     [@option{-I}@var{dir}@dots{}] [@option{-W}@var{warn}@dots{}]
3871     [@option{-M}|@option{-MM}] [@option{-MG}] [@option{-MF} @var{filename}]
3872     [@option{-MP}] [@option{-MQ} @var{target}@dots{}] [@option{-MT} @var{target}@dots{}]
3873     [@option{-x} @var{language}] [@option{-std=}@var{standard}]
3874     @var{infile} @var{outfile}
3876 Only the most useful options are listed here; see below for the remainder.
3877 @c man end
3878 @c man begin SEEALSO
3879 gpl(7), gfdl(7), fsf-funding(7),
3880 gcc(1), as(1), ld(1), and the Info entries for @file{cpp}, @file{gcc}, and
3881 @file{binutils}.
3882 @c man end
3883 @end ignore
3885 @c man begin OPTIONS
3886 The C preprocessor expects two file names as arguments, @var{infile} and
3887 @var{outfile}.  The preprocessor reads @var{infile} together with any
3888 other files it specifies with @samp{#include}.  All the output generated
3889 by the combined input files is written in @var{outfile}.
3891 Either @var{infile} or @var{outfile} may be @option{-}, which as
3892 @var{infile} means to read from standard input and as @var{outfile}
3893 means to write to standard output.  Also, if either file is omitted, it
3894 means the same as if @option{-} had been specified for that file.
3896 Unless otherwise noted, or the option ends in @samp{=}, all options
3897 which take an argument may have that argument appear either immediately
3898 after the option, or with a space between option and argument:
3899 @option{-Ifoo} and @option{-I foo} have the same effect.
3901 @cindex grouping options
3902 @cindex options, grouping
3903 Many options have multi-letter names; therefore multiple single-letter
3904 options may @emph{not} be grouped: @option{-dM} is very different from
3905 @w{@samp{-d -M}}.
3907 @cindex options
3908 @include cppopts.texi
3909 @c man end
3911 @node Environment Variables
3912 @chapter Environment Variables
3913 @cindex environment variables
3914 @c man begin ENVIRONMENT
3916 This section describes the environment variables that affect how CPP
3917 operates.  You can use them to specify directories or prefixes to use
3918 when searching for include files, or to control dependency output.
3920 Note that you can also specify places to search using options such as
3921 @option{-I}, and control dependency output with options like
3922 @option{-M} (@pxref{Invocation}).  These take precedence over
3923 environment variables, which in turn take precedence over the
3924 configuration of GCC@.
3926 @include cppenv.texi
3927 @c man end
3929 @include fdl.texi
3931 @page
3932 @node Option Index
3933 @unnumbered Option Index
3935 CPP's command line options are indexed here without any initial
3936 @samp{-} or @samp{--}.
3938 @printindex op
3940 @node Index of Directives
3941 @unnumbered Index of Directives
3942 @printindex fn
3944 @node Concept Index
3945 @unnumbered Concept Index
3946 @printindex cp
3948 @bye