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