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 1679@noindent 1680The above explanation is ambiguous about the case where the only macro 1681parameter is a variable arguments parameter, as it is meaningless to 1682try to distinguish whether no argument at all is an empty argument or 1683a missing argument. In this case the C99 standard is clear that the 1684comma must remain, however the existing GCC extension used to swallow 1685the comma. So CPP retains the comma when conforming to a specific C 1686standard, and drops it otherwise. 1687 1688C99 mandates that the only place the identifier @code{@w{__VA_ARGS__}} 1689can appear is in the replacement list of a variadic macro. It may not 1690be used as a macro name, macro argument name, or within a different type 1691of macro. It may also be forbidden in open text; the standard is 1692ambiguous. We recommend you avoid using it except for its defined 1693purpose. 1694 1695Variadic macros are a new feature in C99. GNU CPP has supported them 1696for a long time, but only with a named variable argument 1697(@samp{args@dots{}}, not @samp{@dots{}} and @code{@w{__VA_ARGS__}}). If you are 1698concerned with portability to previous versions of GCC, you should use 1699only named variable arguments. On the other hand, if you are concerned 1700with portability to other conforming implementations of C99, you should 1701use only @code{@w{__VA_ARGS__}}. 1702 1703Previous versions of GNU CPP implemented the comma-deletion extension 1704much more generally. We have restricted it in this release to minimize 1705the differences from C99. To get the same effect with both this and 1706previous versions of GCC, the token preceding the special @samp{##} must 1707be a comma, and there must be white space between that comma and 1708whatever comes immediately before it: 1709 1710@example 1711#define eprintf(format, args@dots{}) fprintf (stderr, format , ##args) 1712@end example 1713 1714@noindent 1715@xref{Differences from previous versions}, for the gory details. 1716 1717@node Predefined Macros 1718@section Predefined Macros 1719 1720@cindex predefined macros 1721Several object-like macros are predefined; you use them without 1722supplying their definitions. They fall into three classes: standard, 1723common, and system-specific. 1724 1725In C++, there is a fourth category, the named operators. They act like 1726predefined macros, but you cannot undefine them. 1727 1728@menu 1729* Standard Predefined Macros:: 1730* Common Predefined Macros:: 1731* System-specific Predefined Macros:: 1732* C++ Named Operators:: 1733@end menu 1734 1735@node Standard Predefined Macros 1736@subsection Standard Predefined Macros 1737@cindex standard predefined macros. 1738 1739The standard predefined macros are specified by the C and/or C++ 1740language standards, so they are available with all compilers that 1741implement those standards. Older compilers may not provide all of 1742them. Their names all start with double underscores. 1743 1744@table @code 1745@item __FILE__ 1746This macro expands to the name of the current input file, in the form of 1747a C string constant. This is the path by which the preprocessor opened 1748the file, not the short name specified in @samp{#include} or as the 1749input file name argument. For example, 1750@code{"/usr/local/include/myheader.h"} is a possible expansion of this 1751macro. 1752 1753@item __LINE__ 1754This macro expands to the current input line number, in the form of a 1755decimal integer constant. While we call it a predefined macro, it's 1756a pretty strange macro, since its ``definition'' changes with each 1757new line of source code. 1758@end table 1759 1760@code{__FILE__} and @code{__LINE__} are useful in generating an error 1761message to report an inconsistency detected by the program; the message 1762can state the source line at which the inconsistency was detected. For 1763example, 1764 1765@example 1766fprintf (stderr, "Internal error: " 1767 "negative string length " 1768 "%d at %s, line %d.", 1769 length, __FILE__, __LINE__); 1770@end example 1771 1772An @samp{#include} directive changes the expansions of @code{__FILE__} 1773and @code{__LINE__} to correspond to the included file. At the end of 1774that file, when processing resumes on the input file that contained 1775the @samp{#include} directive, the expansions of @code{__FILE__} and 1776@code{__LINE__} revert to the values they had before the 1777@samp{#include} (but @code{__LINE__} is then incremented by one as 1778processing moves to the line after the @samp{#include}). 1779 1780A @samp{#line} directive changes @code{__LINE__}, and may change 1781@code{__FILE__} as well. @xref{Line Control}. 1782 1783C99 introduces @code{__func__}, and GCC has provided @code{__FUNCTION__} 1784for a long time. Both of these are strings containing the name of the 1785current function (there are slight semantic differences; see the GCC 1786manual). Neither of them is a macro; the preprocessor does not know the 1787name of the current function. They tend to be useful in conjunction 1788with @code{__FILE__} and @code{__LINE__}, though. 1789 1790@table @code 1791 1792@item __DATE__ 1793This macro expands to a string constant that describes the date on which 1794the preprocessor is being run. The string constant contains eleven 1795characters and looks like @code{@w{"Feb 12 1996"}}. If the day of the 1796month is less than 10, it is padded with a space on the left. 1797 1798@item __TIME__ 1799This macro expands to a string constant that describes the time at 1800which the preprocessor is being run. The string constant contains 1801eight characters and looks like @code{"23:59:01"}. 1802 1803@item __STDC__ 1804In normal operation, this macro expands to the constant 1, to signify 1805that this compiler conforms to ISO Standard C@. If GNU CPP is used with 1806a compiler other than GCC, this is not necessarily true; however, the 1807preprocessor always conforms to the standard, unless the 1808@option{-traditional} option is used. 1809 1810This macro is not defined if the @option{-traditional} option is used. 1811 1812On some hosts, the system compiler uses a different convention, where 1813@code{__STDC__} is normally 0, but is 1 if the user specifies strict 1814conformance to the C Standard. GNU CPP follows the host convention when 1815processing system header files, but when processing user files 1816@code{__STDC__} is always 1. This has been reported to cause problems; 1817for instance, some versions of Solaris provide X Windows headers that 1818expect @code{__STDC__} to be either undefined or 1. You may be able to 1819work around this sort of problem by using an @option{-I} option to 1820cancel treatment of those headers as system headers. @xref{Invocation}. 1821 1822@item __STDC_VERSION__ 1823This macro expands to the C Standard's version number, a long integer 1824constant of the form @code{@var{yyyy}@var{mm}L} where @var{yyyy} and 1825@var{mm} are the year and month of the Standard version. This signifies 1826which version of the C Standard the compiler conforms to. Like 1827@code{__STDC__}, this is not necessarily accurate for the entire 1828implementation, unless GNU CPP is being used with GCC@. 1829 1830The value @code{199409L} signifies the 1989 C standard as amended in 18311994, which is the current default; the value @code{199901L} signifies 1832the 1999 revision of the C standard. Support for the 1999 revision is 1833not yet complete. 1834 1835This macro is not defined if the @option{-traditional} option is used, nor 1836when compiling C++ or Objective-C@. 1837 1838@item __STDC_HOSTED__ 1839This macro is defined, with value 1, if the compiler's target is a 1840@dfn{hosted environment}. A hosted environment has the complete 1841facilities of the standard C library available. 1842 1843@item __cplusplus 1844This macro is defined when the C++ compiler is in use. You can use 1845@code{__cplusplus} to test whether a header is compiled by a C compiler 1846or a C++ compiler. This macro is similar to @code{__STDC_VERSION__}, in 1847that it expands to a version number. A fully conforming implementation 1848of the 1998 C++ standard will define this macro to @code{199711L}. The 1849GNU C++ compiler is not yet fully conforming, so it uses @code{1} 1850instead. We hope to complete our implementation in the near future. 1851 1852@end table 1853 1854@node Common Predefined Macros 1855@subsection Common Predefined Macros 1856@cindex common predefined macros 1857 1858The common predefined macros are GNU C extensions. They are available 1859with the same meanings regardless of the machine or operating system on 1860which you are using GNU C@. Their names all start with double 1861underscores. 1862 1863@table @code 1864 1865@item __GNUC__ 1866@itemx __GNUC_MINOR__ 1867@itemx __GNUC_PATCHLEVEL__ 1868These macros are defined by all GNU compilers that use the C 1869preprocessor: C, C++, and Objective-C@. Their values are the major 1870version, minor version, and patch level of the compiler, as integer 1871constants. For example, GCC 3.2.1 will define @code{__GNUC__} to 3, 1872@code{__GNUC_MINOR__} to 2, and @code{__GNUC_PATCHLEVEL__} to 1. They 1873are defined only when the entire compiler is in use; if you invoke the 1874preprocessor directly, they are not defined. 1875 1876@code{__GNUC_PATCHLEVEL__} is new to GCC 3.0; it is also present in the 1877widely-used development snapshots leading up to 3.0 (which identify 1878themselves as GCC 2.96 or 2.97, depending on which snapshot you have). 1879 1880If all you need to know is whether or not your program is being compiled 1881by GCC, you can simply test @code{__GNUC__}. If you need to write code 1882which depends on a specific version, you must be more careful. Each 1883time the minor version is increased, the patch level is reset to zero; 1884each time the major version is increased (which happens rarely), the 1885minor version and patch level are reset. If you wish to use the 1886predefined macros directly in the conditional, you will need to write it 1887like this: 1888 1889@example 1890/* @r{Test for GCC > 3.2.0} */ 1891#if __GNUC__ > 3 || \ 1892 (__GNUC__ == 3 && (__GNUC_MINOR__ > 2 || \ 1893 (__GNUC_MINOR__ == 2 && \ 1894 __GNUC_PATCHLEVEL__ > 0)) 1895@end example 1896 1897@noindent 1898Another approach is to use the predefined macros to 1899calculate a single number, then compare that against a threshold: 1900 1901@example 1902#define GCC_VERSION (__GNUC__ * 10000 \ 1903 + __GNUC_MINOR__ * 100 \ 1904 + __GNUC_PATCHLEVEL__) 1905@dots{} 1906/* @r{Test for GCC > 3.2.0} */ 1907#if GCC_VERSION > 30200 1908@end example 1909 1910@noindent 1911Many people find this form easier to understand. 1912 1913@item __OBJC__ 1914This macro is defined, with value 1, when the Objective-C compiler is in 1915use. You can use @code{__OBJC__} to test whether a header is compiled 1916by a C compiler or a Objective-C compiler. 1917 1918@item __GNUG__ 1919The GNU C++ compiler defines this. Testing it is equivalent to 1920testing @code{@w{(__GNUC__ && __cplusplus)}}. 1921 1922@item __STRICT_ANSI__ 1923GCC defines this macro if and only if the @option{-ansi} switch, or a 1924@option{-std} switch specifying strict conformance to some version of ISO C, 1925was specified when GCC was invoked. It is defined to @samp{1}. 1926This macro exists primarily to direct GNU libc's header files to 1927restrict their definitions to the minimal set found in the 1989 C 1928standard. 1929 1930@item __BASE_FILE__ 1931This macro expands to the name of the main input file, in the form 1932of a C string constant. This is the source file that was specified 1933on the command line of the preprocessor or C compiler. 1934 1935@item __INCLUDE_LEVEL__ 1936This macro expands to a decimal integer constant that represents the 1937depth of nesting in include files. The value of this macro is 1938incremented on every @samp{#include} directive and decremented at the 1939end of every included file. It starts out at 0, it's value within the 1940base file specified on the command line. 1941 1942@item __VERSION__ 1943This macro expands to a string constant which describes the version of 1944the compiler in use. You should not rely on its contents having any 1945particular form, but it can be counted on to contain at least the 1946release number. 1947 1948@item __OPTIMIZE__ 1949@itemx __OPTIMIZE_SIZE__ 1950@itemx __NO_INLINE__ 1951These macros describe the compilation mode. @code{__OPTIMIZE__} is 1952defined in all optimizing compilations. @code{__OPTIMIZE_SIZE__} is 1953defined if the compiler is optimizing for size, not speed. 1954@code{__NO_INLINE__} is defined if no functions will be inlined into 1955their callers (when not optimizing, or when inlining has been 1956specifically disabled by @option{-fno-inline}). 1957 1958These macros cause certain GNU header files to provide optimized 1959definitions, using macros or inline functions, of system library 1960functions. You should not use these macros in any way unless you make 1961sure that programs will execute with the same effect whether or not they 1962are defined. If they are defined, their value is 1. 1963 1964@item __CHAR_UNSIGNED__ 1965GCC defines this macro if and only if the data type @code{char} is 1966unsigned on the target machine. It exists to cause the standard header 1967file @file{limits.h} to work correctly. You should not use this macro 1968yourself; instead, refer to the standard macros defined in @file{limits.h}. 1969 1970@item __REGISTER_PREFIX__ 1971This macro expands to a single token (not a string constant) which is 1972the prefix applied to CPU register names in assembly language for this 1973target. You can use it to write assembly that is usable in multiple 1974environments. For example, in the @code{m68k-aout} environment it 1975expands to nothing, but in the @code{m68k-coff} environment it expands 1976to a single @samp{%}. 1977 1978@item __USER_LABEL_PREFIX__ 1979This macro expands to a single token which is the prefix applied to 1980user labels (symbols visible to C code) in assembly. For example, in 1981the @code{m68k-aout} environment it expands to an @samp{_}, but in the 1982@code{m68k-coff} environment it expands to nothing. 1983 1984This macro will have the correct definition even if 1985@option{-f(no-)underscores} is in use, but it will not be correct if 1986target-specific options that adjust this prefix are used (e.g.@: the 1987OSF/rose @option{-mno-underscores} option). 1988 1989@item __SIZE_TYPE__ 1990@itemx __PTRDIFF_TYPE__ 1991@itemx __WCHAR_TYPE__ 1992@itemx __WINT_TYPE__ 1993These macros are defined to the correct underlying types for the 1994@code{size_t}, @code{ptrdiff_t}, @code{wchar_t}, and @code{wint_t} 1995typedefs, respectively. They exist to make the standard header files 1996@file{stddef.h} and @file{wchar.h} work correctly. You should not use 1997these macros directly; instead, include the appropriate headers and use 1998the typedefs. 1999 2000@item __USING_SJLJ_EXCEPTIONS__ 2001This macro is defined, with value 1, if the compiler uses the old 2002mechanism based on @code{setjmp} and @code{longjmp} for exception 2003handling. 2004@end table 2005 2006@node System-specific Predefined Macros 2007@subsection System-specific Predefined Macros 2008 2009@cindex system-specific predefined macros 2010@cindex predefined macros, system-specific 2011@cindex reserved namespace 2012 2013The C preprocessor normally predefines several macros that indicate what 2014type of system and machine is in use. They are obviously different on 2015each target supported by GCC@. This manual, being for all systems and 2016machines, cannot tell you what their names are, but you can use 2017@command{cpp -dM} to see them all. @xref{Invocation}. All system-specific 2018predefined macros expand to the constant 1, so you can test them with 2019either @samp{#ifdef} or @samp{#if}. 2020 2021The C standard requires that all system-specific macros be part of the 2022@dfn{reserved namespace}. All names which begin with two underscores, 2023or an underscore and a capital letter, are reserved for the compiler and 2024library to use as they wish. However, historically system-specific 2025macros have had names with no special prefix; for instance, it is common 2026to find @code{unix} defined on Unix systems. For all such macros, GCC 2027provides a parallel macro with two underscores added at the beginning 2028and the end. If @code{unix} is defined, @code{__unix__} will be defined 2029too. There will never be more than two underscores; the parallel of 2030@code{_mips} is @code{__mips__}. 2031 2032When the @option{-ansi} option, or any @option{-std} option that 2033requests strict conformance, is given to the compiler, all the 2034system-specific predefined macros outside the reserved namespace are 2035suppressed. The parallel macros, inside the reserved namespace, remain 2036defined. 2037 2038We are slowly phasing out all predefined macros which are outside the 2039reserved namespace. You should never use them in new programs, and we 2040encourage you to correct older code to use the parallel macros whenever 2041you find it. We don't recommend you use the system-specific macros that 2042are in the reserved namespace, either. It is better in the long run to 2043check specifically for features you need, using a tool such as 2044@command{autoconf}. 2045 2046@node C++ Named Operators 2047@subsection C++ Named Operators 2048@cindex named operators 2049@cindex C++ named operators 2050@cindex iso646.h 2051 2052In C++, there are eleven keywords which are simply alternate spellings 2053of operators normally written with punctuation. These keywords are 2054treated as such even in the preprocessor. They function as operators in 2055@samp{#if}, and they cannot be defined as macros or poisoned. In C, you 2056can request that those keywords take their C++ meaning by including 2057@file{iso646.h}. That header defines each one as a normal object-like 2058macro expanding to the appropriate punctuator. 2059 2060These are the named operators and their corresponding punctuators: 2061 2062@multitable {Named Operator} {Punctuator} 2063@item Named Operator @tab Punctuator 2064@item @code{and} @tab @code{&&} 2065@item @code{and_eq} @tab @code{&=} 2066@item @code{bitand} @tab @code{&} 2067@item @code{bitor} @tab @code{|} 2068@item @code{compl} @tab @code{~} 2069@item @code{not} @tab @code{!} 2070@item @code{not_eq} @tab @code{!=} 2071@item @code{or} @tab @code{||} 2072@item @code{or_eq} @tab @code{|=} 2073@item @code{xor} @tab @code{^} 2074@item @code{xor_eq} @tab @code{^=} 2075@end multitable 2076 2077@node Undefining and Redefining Macros 2078@section Undefining and Redefining Macros 2079@cindex undefining macros 2080@cindex redefining macros 2081@findex #undef 2082 2083If a macro ceases to be useful, it may be @dfn{undefined} with the 2084@samp{#undef} directive. @samp{#undef} takes a single argument, the 2085name of the macro to undefine. You use the bare macro name, even if the 2086macro is function-like. It is an error if anything appears on the line 2087after the macro name. @samp{#undef} has no effect if the name is not a 2088macro. 2089 2090@example 2091#define FOO 4 2092x = FOO; @expansion{} x = 4; 2093#undef FOO 2094x = FOO; @expansion{} x = FOO; 2095@end example 2096 2097Once a macro has been undefined, that identifier may be @dfn{redefined} 2098as a macro by a subsequent @samp{#define} directive. The new definition 2099need not have any resemblance to the old definition. 2100 2101However, if an identifier which is currently a macro is redefined, then 2102the new definition must be @dfn{effectively the same} as the old one. 2103Two macro definitions are effectively the same if: 2104@itemize @bullet 2105@item Both are the same type of macro (object- or function-like). 2106@item All the tokens of the replacement list are the same. 2107@item If there are any parameters, they are the same. 2108@item Whitespace appears in the same places in both. It need not be 2109exactly the same amount of whitespace, though. Remember that comments 2110count as whitespace. 2111@end itemize 2112 2113@noindent 2114These definitions are effectively the same: 2115@example 2116#define FOUR (2 + 2) 2117#define FOUR (2 + 2) 2118#define FOUR (2 /* two */ + 2) 2119@end example 2120@noindent 2121but these are not: 2122@example 2123#define FOUR (2 + 2) 2124#define FOUR ( 2+2 ) 2125#define FOUR (2 * 2) 2126#define FOUR(score,and,seven,years,ago) (2 + 2) 2127@end example 2128 2129If a macro is redefined with a definition that is not effectively the 2130same as the old one, the preprocessor issues a warning and changes the 2131macro to use the new definition. If the new definition is effectively 2132the same, the redefinition is silently ignored. This allows, for 2133instance, two different headers to define a common macro. The 2134preprocessor will only complain if the definitions do not match. 2135 2136@node Macro Pitfalls 2137@section Macro Pitfalls 2138@cindex problems with macros 2139@cindex pitfalls of macros 2140 2141In this section we describe some special rules that apply to macros and 2142macro expansion, and point out certain cases in which the rules have 2143counter-intuitive consequences that you must watch out for. 2144 2145@menu 2146* Misnesting:: 2147* Operator Precedence Problems:: 2148* Swallowing the Semicolon:: 2149* Duplication of Side Effects:: 2150* Self-Referential Macros:: 2151* Argument Prescan:: 2152* Newlines in Arguments:: 2153@end menu 2154 2155@node Misnesting 2156@subsection Misnesting 2157 2158When a macro is called with arguments, the arguments are substituted 2159into the macro body and the result is checked, together with the rest of 2160the input file, for more macro calls. It is possible to piece together 2161a macro call coming partially from the macro body and partially from the 2162arguments. For example, 2163 2164@example 2165#define twice(x) (2*(x)) 2166#define call_with_1(x) x(1) 2167call_with_1 (twice) 2168 @expansion{} twice(1) 2169 @expansion{} (2*(1)) 2170@end example 2171 2172Macro definitions do not have to have balanced parentheses. By writing 2173an unbalanced open parenthesis in a macro body, it is possible to create 2174a macro call that begins inside the macro body but ends outside of it. 2175For example, 2176 2177@example 2178#define strange(file) fprintf (file, "%s %d", 2179@dots{} 2180strange(stderr) p, 35) 2181 @expansion{} fprintf (stderr, "%s %d", p, 35) 2182@end example 2183 2184The ability to piece together a macro call can be useful, but the use of 2185unbalanced open parentheses in a macro body is just confusing, and 2186should be avoided. 2187 2188@node Operator Precedence Problems 2189@subsection Operator Precedence Problems 2190@cindex parentheses in macro bodies 2191 2192You may have noticed that in most of the macro definition examples shown 2193above, each occurrence of a macro argument name had parentheses around 2194it. In addition, another pair of parentheses usually surround the 2195entire macro definition. Here is why it is best to write macros that 2196way. 2197 2198Suppose you define a macro as follows, 2199 2200@example 2201#define ceil_div(x, y) (x + y - 1) / y 2202@end example 2203 2204@noindent 2205whose purpose is to divide, rounding up. (One use for this operation is 2206to compute how many @code{int} objects are needed to hold a certain 2207number of @code{char} objects.) Then suppose it is used as follows: 2208 2209@example 2210a = ceil_div (b & c, sizeof (int)); 2211 @expansion{} a = (b & c + sizeof (int) - 1) / sizeof (int); 2212@end example 2213 2214@noindent 2215This does not do what is intended. The operator-precedence rules of 2216C make it equivalent to this: 2217 2218@example 2219a = (b & (c + sizeof (int) - 1)) / sizeof (int); 2220@end example 2221 2222@noindent 2223What we want is this: 2224 2225@example 2226a = ((b & c) + sizeof (int) - 1)) / sizeof (int); 2227@end example 2228 2229@noindent 2230Defining the macro as 2231 2232@example 2233#define ceil_div(x, y) ((x) + (y) - 1) / (y) 2234@end example 2235 2236@noindent 2237provides the desired result. 2238 2239Unintended grouping can result in another way. Consider @code{sizeof 2240ceil_div(1, 2)}. That has the appearance of a C expression that would 2241compute the size of the type of @code{ceil_div (1, 2)}, but in fact it 2242means something very different. Here is what it expands to: 2243 2244@example 2245sizeof ((1) + (2) - 1) / (2) 2246@end example 2247 2248@noindent 2249This would take the size of an integer and divide it by two. The 2250precedence rules have put the division outside the @code{sizeof} when it 2251was intended to be inside. 2252 2253Parentheses around the entire macro definition prevent such problems. 2254Here, then, is the recommended way to define @code{ceil_div}: 2255 2256@example 2257#define ceil_div(x, y) (((x) + (y) - 1) / (y)) 2258@end example 2259 2260@node Swallowing the Semicolon 2261@subsection Swallowing the Semicolon 2262@cindex semicolons (after macro calls) 2263 2264Often it is desirable to define a macro that expands into a compound 2265statement. Consider, for example, the following macro, that advances a 2266pointer (the argument @code{p} says where to find it) across whitespace 2267characters: 2268 2269@example 2270#define SKIP_SPACES(p, limit) \ 2271@{ char *lim = (limit); \ 2272 while (p < lim) @{ \ 2273 if (*p++ != ' ') @{ \ 2274 p--; break; @}@}@} 2275@end example 2276 2277@noindent 2278Here backslash-newline is used to split the macro definition, which must 2279be a single logical line, so that it resembles the way such code would 2280be laid out if not part of a macro definition. 2281 2282A call to this macro might be @code{SKIP_SPACES (p, lim)}. Strictly 2283speaking, the call expands to a compound statement, which is a complete 2284statement with no need for a semicolon to end it. However, since it 2285looks like a function call, it minimizes confusion if you can use it 2286like a function call, writing a semicolon afterward, as in 2287@code{SKIP_SPACES (p, lim);} 2288 2289This can cause trouble before @code{else} statements, because the 2290semicolon is actually a null statement. Suppose you write 2291 2292@example 2293if (*p != 0) 2294 SKIP_SPACES (p, lim); 2295else @dots{} 2296@end example 2297 2298@noindent 2299The presence of two statements---the compound statement and a null 2300statement---in between the @code{if} condition and the @code{else} 2301makes invalid C code. 2302 2303The definition of the macro @code{SKIP_SPACES} can be altered to solve 2304this problem, using a @code{do @dots{} while} statement. Here is how: 2305 2306@example 2307#define SKIP_SPACES(p, limit) \ 2308do @{ char *lim = (limit); \ 2309 while (p < lim) @{ \ 2310 if (*p++ != ' ') @{ \ 2311 p--; break; @}@}@} \ 2312while (0) 2313@end example 2314 2315Now @code{SKIP_SPACES (p, lim);} expands into 2316 2317@example 2318do @{@dots{}@} while (0); 2319@end example 2320 2321@noindent 2322which is one statement. The loop executes exactly once; most compilers 2323generate no extra code for it. 2324 2325@node Duplication of Side Effects 2326@subsection Duplication of Side Effects 2327 2328@cindex side effects (in macro arguments) 2329@cindex unsafe macros 2330Many C programs define a macro @code{min}, for ``minimum'', like this: 2331 2332@example 2333#define min(X, Y) ((X) < (Y) ? (X) : (Y)) 2334@end example 2335 2336When you use this macro with an argument containing a side effect, 2337as shown here, 2338 2339@example 2340next = min (x + y, foo (z)); 2341@end example 2342 2343@noindent 2344it expands as follows: 2345 2346@example 2347next = ((x + y) < (foo (z)) ? (x + y) : (foo (z))); 2348@end example 2349 2350@noindent 2351where @code{x + y} has been substituted for @code{X} and @code{foo (z)} 2352for @code{Y}. 2353 2354The function @code{foo} is used only once in the statement as it appears 2355in the program, but the expression @code{foo (z)} has been substituted 2356twice into the macro expansion. As a result, @code{foo} might be called 2357two times when the statement is executed. If it has side effects or if 2358it takes a long time to compute, the results might not be what you 2359intended. We say that @code{min} is an @dfn{unsafe} macro. 2360 2361The best solution to this problem is to define @code{min} in a way that 2362computes the value of @code{foo (z)} only once. The C language offers 2363no standard way to do this, but it can be done with GNU extensions as 2364follows: 2365 2366@example 2367#define min(X, Y) \ 2368(@{ typeof (X) x_ = (X); \ 2369 typeof (Y) y_ = (Y); \ 2370 (x_ < y_) ? x_ : y_; @}) 2371@end example 2372 2373The @samp{(@{ @dots{} @})} notation produces a compound statement that 2374acts as an expression. Its value is the value of its last statement. 2375This permits us to define local variables and assign each argument to 2376one. The local variables have underscores after their names to reduce 2377the risk of conflict with an identifier of wider scope (it is impossible 2378to avoid this entirely). Now each argument is evaluated exactly once. 2379 2380If you do not wish to use GNU C extensions, the only solution is to be 2381careful when @emph{using} the macro @code{min}. For example, you can 2382calculate the value of @code{foo (z)}, save it in a variable, and use 2383that variable in @code{min}: 2384 2385@example 2386@group 2387#define min(X, Y) ((X) < (Y) ? (X) : (Y)) 2388@dots{} 2389@{ 2390 int tem = foo (z); 2391 next = min (x + y, tem); 2392@} 2393@end group 2394@end example 2395 2396@noindent 2397(where we assume that @code{foo} returns type @code{int}). 2398 2399@node Self-Referential Macros 2400@subsection Self-Referential Macros 2401@cindex self-reference 2402 2403A @dfn{self-referential} macro is one whose name appears in its 2404definition. Recall that all macro definitions are rescanned for more 2405macros to replace. If the self-reference were considered a use of the 2406macro, it would produce an infinitely large expansion. To prevent this, 2407the self-reference is not considered a macro call. It is passed into 2408the preprocessor output unchanged. Let's consider an example: 2409 2410@example 2411#define foo (4 + foo) 2412@end example 2413 2414@noindent 2415where @code{foo} is also a variable in your program. 2416 2417Following the ordinary rules, each reference to @code{foo} will expand 2418into @code{(4 + foo)}; then this will be rescanned and will expand into 2419@code{(4 + (4 + foo))}; and so on until the computer runs out of memory. 2420 2421The self-reference rule cuts this process short after one step, at 2422@code{(4 + foo)}. Therefore, this macro definition has the possibly 2423useful effect of causing the program to add 4 to the value of @code{foo} 2424wherever @code{foo} is referred to. 2425 2426In most cases, it is a bad idea to take advantage of this feature. A 2427person reading the program who sees that @code{foo} is a variable will 2428not expect that it is a macro as well. The reader will come across the 2429identifier @code{foo} in the program and think its value should be that 2430of the variable @code{foo}, whereas in fact the value is four greater. 2431 2432One common, useful use of self-reference is to create a macro which 2433expands to itself. If you write 2434 2435@example 2436#define EPERM EPERM 2437@end example 2438 2439@noindent 2440then the macro @code{EPERM} expands to @code{EPERM}. Effectively, it is 2441left alone by the preprocessor whenever it's used in running text. You 2442can tell that it's a macro with @samp{#ifdef}. You might do this if you 2443want to define numeric constants with an @code{enum}, but have 2444@samp{#ifdef} be true for each constant. 2445 2446If a macro @code{x} expands to use a macro @code{y}, and the expansion of 2447@code{y} refers to the macro @code{x}, that is an @dfn{indirect 2448self-reference} of @code{x}. @code{x} is not expanded in this case 2449either. Thus, if we have 2450 2451@example 2452#define x (4 + y) 2453#define y (2 * x) 2454@end example 2455 2456@noindent 2457then @code{x} and @code{y} expand as follows: 2458 2459@example 2460@group 2461x @expansion{} (4 + y) 2462 @expansion{} (4 + (2 * x)) 2463 2464y @expansion{} (2 * x) 2465 @expansion{} (2 * (4 + y)) 2466@end group 2467@end example 2468 2469@noindent 2470Each macro is expanded when it appears in the definition of the other 2471macro, but not when it indirectly appears in its own definition. 2472 2473@node Argument Prescan 2474@subsection Argument Prescan 2475@cindex expansion of arguments 2476@cindex macro argument expansion 2477@cindex prescan of macro arguments 2478 2479Macro arguments are completely macro-expanded before they are 2480substituted into a macro body, unless they are stringified or pasted 2481with other tokens. After substitution, the entire macro body, including 2482the substituted arguments, is scanned again for macros to be expanded. 2483The result is that the arguments are scanned @emph{twice} to expand 2484macro calls in them. 2485 2486Most of the time, this has no effect. If the argument contained any 2487macro calls, they are expanded during the first scan. The result 2488therefore contains no macro calls, so the second scan does not change 2489it. If the argument were substituted as given, with no prescan, the 2490single remaining scan would find the same macro calls and produce the 2491same results. 2492 2493You might expect the double scan to change the results when a 2494self-referential macro is used in an argument of another macro 2495(@pxref{Self-Referential Macros}): the self-referential macro would be 2496expanded once in the first scan, and a second time in the second scan. 2497However, this is not what happens. The self-references that do not 2498expand in the first scan are marked so that they will not expand in the 2499second scan either. 2500 2501You might wonder, ``Why mention the prescan, if it makes no difference? 2502And why not skip it and make the preprocessor faster?'' The answer is 2503that the prescan does make a difference in three special cases: 2504 2505@itemize @bullet 2506@item 2507Nested calls to a macro. 2508 2509We say that @dfn{nested} calls to a macro occur when a macro's argument 2510contains a call to that very macro. For example, if @code{f} is a macro 2511that expects one argument, @code{f (f (1))} is a nested pair of calls to 2512@code{f}. The desired expansion is made by expanding @code{f (1)} and 2513substituting that into the definition of @code{f}. The prescan causes 2514the expected result to happen. Without the prescan, @code{f (1)} itself 2515would be substituted as an argument, and the inner use of @code{f} would 2516appear during the main scan as an indirect self-reference and would not 2517be expanded. 2518 2519@item 2520Macros that call other macros that stringify or concatenate. 2521 2522If an argument is stringified or concatenated, the prescan does not 2523occur. If you @emph{want} to expand a macro, then stringify or 2524concatenate its expansion, you can do that by causing one macro to call 2525another macro that does the stringification or concatenation. For 2526instance, if you have 2527 2528@example 2529#define AFTERX(x) X_ ## x 2530#define XAFTERX(x) AFTERX(x) 2531#define TABLESIZE 1024 2532#define BUFSIZE TABLESIZE 2533@end example 2534 2535then @code{AFTERX(BUFSIZE)} expands to @code{X_BUFSIZE}, and 2536@code{XAFTERX(BUFSIZE)} expands to @code{X_1024}. (Not to 2537@code{X_TABLESIZE}. Prescan always does a complete expansion.) 2538 2539@item 2540Macros used in arguments, whose expansions contain unshielded commas. 2541 2542This can cause a macro expanded on the second scan to be called with the 2543wrong number of arguments. Here is an example: 2544 2545@example 2546#define foo a,b 2547#define bar(x) lose(x) 2548#define lose(x) (1 + (x)) 2549@end example 2550 2551We would like @code{bar(foo)} to turn into @code{(1 + (foo))}, which 2552would then turn into @code{(1 + (a,b))}. Instead, @code{bar(foo)} 2553expands into @code{lose(a,b)}, and you get an error because @code{lose} 2554requires a single argument. In this case, the problem is easily solved 2555by the same parentheses that ought to be used to prevent misnesting of 2556arithmetic operations: 2557 2558@example 2559#define foo (a,b) 2560@exdent or 2561#define bar(x) lose((x)) 2562@end example 2563 2564The extra pair of parentheses prevents the comma in @code{foo}'s 2565definition from being interpreted as an argument separator. 2566 2567@end itemize 2568 2569@node Newlines in Arguments 2570@subsection Newlines in Arguments 2571@cindex newlines in macro arguments 2572 2573The invocation of a function-like macro can extend over many logical 2574lines. However, in the present implementation, the entire expansion 2575comes out on one line. Thus line numbers emitted by the compiler or 2576debugger refer to the line the invocation started on, which might be 2577different to the line containing the argument causing the problem. 2578 2579Here is an example illustrating this: 2580 2581@example 2582#define ignore_second_arg(a,b,c) a; c 2583 2584ignore_second_arg (foo (), 2585 ignored (), 2586 syntax error); 2587@end example 2588 2589@noindent 2590The syntax error triggered by the tokens @code{syntax error} results in 2591an error message citing line three---the line of ignore_second_arg--- 2592even though the problematic code comes from line five. 2593 2594We consider this a bug, and intend to fix it in the near future. 2595 2596@node Conditionals 2597@chapter Conditionals 2598@cindex conditionals 2599 2600A @dfn{conditional} is a directive that instructs the preprocessor to 2601select whether or not to include a chunk of code in the final token 2602stream passed to the compiler. Preprocessor conditionals can test 2603arithmetic expressions, or whether a name is defined as a macro, or both 2604simultaneously using the special @code{defined} operator. 2605 2606A conditional in the C preprocessor resembles in some ways an @code{if} 2607statement in C, but it is important to understand the difference between 2608them. The condition in an @code{if} statement is tested during the 2609execution of your program. Its purpose is to allow your program to 2610behave differently from run to run, depending on the data it is 2611operating on. The condition in a preprocessing conditional directive is 2612tested when your program is compiled. Its purpose is to allow different 2613code to be included in the program depending on the situation at the 2614time of compilation. 2615 2616However, the distinction is becoming less clear. Modern compilers often 2617do test @code{if} statements when a program is compiled, if their 2618conditions are known not to vary at run time, and eliminate code which 2619can never be executed. If you can count on your compiler to do this, 2620you may find that your program is more readable if you use @code{if} 2621statements with constant conditions (perhaps determined by macros). Of 2622course, you can only use this to exclude code, not type definitions or 2623other preprocessing directives, and you can only do it if the code 2624remains syntactically valid when it is not to be used. 2625 2626GCC version 3 eliminates this kind of never-executed code even when 2627not optimizing. Older versions did it only when optimizing. 2628 2629@menu 2630* Conditional Uses:: 2631* Conditional Syntax:: 2632* Deleted Code:: 2633@end menu 2634 2635@node Conditional Uses 2636@section Conditional Uses 2637 2638There are three general reasons to use a conditional. 2639 2640@itemize @bullet 2641@item 2642A program may need to use different code depending on the machine or 2643operating system it is to run on. In some cases the code for one 2644operating system may be erroneous on another operating system; for 2645example, it might refer to data types or constants that do not exist on 2646the other system. When this happens, it is not enough to avoid 2647executing the invalid code. Its mere presence will cause the compiler 2648to reject the program. With a preprocessing conditional, the offending 2649code can be effectively excised from the program when it is not valid. 2650 2651@item 2652You may want to be able to compile the same source file into two 2653different programs. One version might make frequent time-consuming 2654consistency checks on its intermediate data, or print the values of 2655those data for debugging, and the other not. 2656 2657@item 2658A conditional whose condition is always false is one way to exclude code 2659from the program but keep it as a sort of comment for future reference. 2660@end itemize 2661 2662Simple programs that do not need system-specific logic or complex 2663debugging hooks generally will not need to use preprocessing 2664conditionals. 2665 2666@node Conditional Syntax 2667@section Conditional Syntax 2668 2669@findex #if 2670A conditional in the C preprocessor begins with a @dfn{conditional 2671directive}: @samp{#if}, @samp{#ifdef} or @samp{#ifndef}. 2672 2673@menu 2674* Ifdef:: 2675* If:: 2676* Defined:: 2677* Else:: 2678* Elif:: 2679@end menu 2680 2681@node Ifdef 2682@subsection Ifdef 2683@findex #ifdef 2684@findex #endif 2685 2686The simplest sort of conditional is 2687 2688@example 2689@group 2690#ifdef @var{MACRO} 2691 2692@var{controlled text} 2693 2694#endif /* @var{MACRO} */ 2695@end group 2696@end example 2697 2698@cindex conditional group 2699This block is called a @dfn{conditional group}. @var{controlled text} 2700will be included in the output of the preprocessor if and only if 2701@var{MACRO} is defined. We say that the conditional @dfn{succeeds} if 2702@var{MACRO} is defined, @dfn{fails} if it is not. 2703 2704The @var{controlled text} inside of a conditional can include 2705preprocessing directives. They are executed only if the conditional 2706succeeds. You can nest conditional groups inside other conditional 2707groups, but they must be completely nested. In other words, 2708@samp{#endif} always matches the nearest @samp{#ifdef} (or 2709@samp{#ifndef}, or @samp{#if}). Also, you cannot start a conditional 2710group in one file and end it in another. 2711 2712Even if a conditional fails, the @var{controlled text} inside it is 2713still run through initial transformations and tokenization. Therefore, 2714it must all be lexically valid C@. Normally the only way this matters is 2715that all comments and string literals inside a failing conditional group 2716must still be properly ended. 2717 2718The comment following the @samp{#endif} is not required, but it is a 2719good practice if there is a lot of @var{controlled text}, because it 2720helps people match the @samp{#endif} to the corresponding @samp{#ifdef}. 2721Older programs sometimes put @var{MACRO} directly after the 2722@samp{#endif} without enclosing it in a comment. This is invalid code 2723according to the C standard. GNU CPP accepts it with a warning. It 2724never affects which @samp{#ifndef} the @samp{#endif} matches. 2725 2726@findex #ifndef 2727Sometimes you wish to use some code if a macro is @emph{not} defined. 2728You can do this by writing @samp{#ifndef} instead of @samp{#ifdef}. 2729One common use of @samp{#ifndef} is to include code only the first 2730time a header file is included. @xref{Once-Only Headers}. 2731 2732Macro definitions can vary between compilations for several reasons. 2733Here are some samples. 2734 2735@itemize @bullet 2736@item 2737Some macros are predefined on each kind of machine 2738(@pxref{System-specific Predefined Macros}). This allows you to provide 2739code specially tuned for a particular machine. 2740 2741@item 2742System header files define more macros, associated with the features 2743they implement. You can test these macros with conditionals to avoid 2744using a system feature on a machine where it is not implemented. 2745 2746@item 2747Macros can be defined or undefined with the @option{-D} and @option{-U} 2748command line options when you compile the program. You can arrange to 2749compile the same source file into two different programs by choosing a 2750macro name to specify which program you want, writing conditionals to 2751test whether or how this macro is defined, and then controlling the 2752state of the macro with command line options, perhaps set in the 2753Makefile. @xref{Invocation}. 2754 2755@item 2756Your program might have a special header file (often called 2757@file{config.h}) that is adjusted when the program is compiled. It can 2758define or not define macros depending on the features of the system and 2759the desired capabilities of the program. The adjustment can be 2760automated by a tool such as @command{autoconf}, or done by hand. 2761@end itemize 2762 2763@node If 2764@subsection If 2765 2766The @samp{#if} directive allows you to test the value of an arithmetic 2767expression, rather than the mere existence of one macro. Its syntax is 2768 2769@example 2770@group 2771#if @var{expression} 2772 2773@var{controlled text} 2774 2775#endif /* @var{expression} */ 2776@end group 2777@end example 2778 2779@var{expression} is a C expression of integer type, subject to stringent 2780restrictions. It may contain 2781 2782@itemize @bullet 2783@item 2784Integer constants. 2785 2786@item 2787Character constants, which are interpreted as they would be in normal 2788code. 2789 2790@item 2791Arithmetic operators for addition, subtraction, multiplication, 2792division, bitwise operations, shifts, comparisons, and logical 2793operations (@code{&&} and @code{||}). The latter two obey the usual 2794short-circuiting rules of standard C@. 2795 2796@item 2797Macros. All macros in the expression are expanded before actual 2798computation of the expression's value begins. 2799 2800@item 2801Uses of the @code{defined} operator, which lets you check whether macros 2802are defined in the middle of an @samp{#if}. 2803 2804@item 2805Identifiers that are not macros, which are all considered to be the 2806number zero. This allows you to write @code{@w{#if MACRO}} instead of 2807@code{@w{#ifdef MACRO}}, if you know that MACRO, when defined, will 2808always have a nonzero value. Function-like macros used without their 2809function call parentheses are also treated as zero. 2810 2811In some contexts this shortcut is undesirable. The @option{-Wundef} 2812option causes GCC to warn whenever it encounters an identifier which is 2813not a macro in an @samp{#if}. 2814@end itemize 2815 2816The preprocessor does not know anything about types in the language. 2817Therefore, @code{sizeof} operators are not recognized in @samp{#if}, and 2818neither are @code{enum} constants. They will be taken as identifiers 2819which are not macros, and replaced by zero. In the case of 2820@code{sizeof}, this is likely to cause the expression to be invalid. 2821 2822The preprocessor calculates the value of @var{expression}. It carries 2823out all calculations in the widest integer type known to the compiler; 2824on most machines supported by GCC this is 64 bits. This is not the same 2825rule as the compiler uses to calculate the value of a constant 2826expression, and may give different results in some cases. If the value 2827comes out to be nonzero, the @samp{#if} succeeds and the @var{controlled 2828text} is included; otherwise it is skipped. 2829 2830If @var{expression} is not correctly formed, GCC issues an error and 2831treats the conditional as having failed. 2832 2833@node Defined 2834@subsection Defined 2835 2836@cindex @code{defined} 2837The special operator @code{defined} is used in @samp{#if} and 2838@samp{#elif} expressions to test whether a certain name is defined as a 2839macro. @code{defined @var{name}} and @code{defined (@var{name})} are 2840both expressions whose value is 1 if @var{name} is defined as a macro at 2841the current point in the program, and 0 otherwise. Thus, @code{@w{#if 2842defined MACRO}} is precisely equivalent to @code{@w{#ifdef MACRO}}. 2843 2844@code{defined} is useful when you wish to test more than one macro for 2845existence at once. For example, 2846 2847@example 2848#if defined (__vax__) || defined (__ns16000__) 2849@end example 2850 2851@noindent 2852would succeed if either of the names @code{__vax__} or 2853@code{__ns16000__} is defined as a macro. 2854 2855Conditionals written like this: 2856 2857@example 2858#if defined BUFSIZE && BUFSIZE >= 1024 2859@end example 2860 2861@noindent 2862can generally be simplified to just @code{@w{#if BUFSIZE >= 1024}}, 2863since if @code{BUFSIZE} is not defined, it will be interpreted as having 2864the value zero. 2865 2866If the @code{defined} operator appears as a result of a macro expansion, 2867the C standard says the behavior is undefined. GNU cpp treats it as a 2868genuine @code{defined} operator and evaluates it normally. It will warn 2869wherever your code uses this feature if you use the command-line option 2870@option{-pedantic}, since other compilers may handle it differently. 2871 2872@node Else 2873@subsection Else 2874 2875@findex #else 2876The @samp{#else} directive can be added to a conditional to provide 2877alternative text to be used if the condition fails. This is what it 2878looks like: 2879 2880@example 2881@group 2882#if @var{expression} 2883@var{text-if-true} 2884#else /* Not @var{expression} */ 2885@var{text-if-false} 2886#endif /* Not @var{expression} */ 2887@end group 2888@end example 2889 2890@noindent 2891If @var{expression} is nonzero, the @var{text-if-true} is included and 2892the @var{text-if-false} is skipped. If @var{expression} is zero, the 2893opposite happens. 2894 2895You can use @samp{#else} with @samp{#ifdef} and @samp{#ifndef}, too. 2896 2897@node Elif 2898@subsection Elif 2899 2900@findex #elif 2901One common case of nested conditionals is used to check for more than two 2902possible alternatives. For example, you might have 2903 2904@example 2905#if X == 1 2906@dots{} 2907#else /* X != 1 */ 2908#if X == 2 2909@dots{} 2910#else /* X != 2 */ 2911@dots{} 2912#endif /* X != 2 */ 2913#endif /* X != 1 */ 2914@end example 2915 2916Another conditional directive, @samp{#elif}, allows this to be 2917abbreviated as follows: 2918 2919@example 2920#if X == 1 2921@dots{} 2922#elif X == 2 2923@dots{} 2924#else /* X != 2 and X != 1*/ 2925@dots{} 2926#endif /* X != 2 and X != 1*/ 2927@end example 2928 2929@samp{#elif} stands for ``else if''. Like @samp{#else}, it goes in the 2930middle of a conditional group and subdivides it; it does not require a 2931matching @samp{#endif} of its own. Like @samp{#if}, the @samp{#elif} 2932directive includes an expression to be tested. The text following the 2933@samp{#elif} is processed only if the original @samp{#if}-condition 2934failed and the @samp{#elif} condition succeeds. 2935 2936More than one @samp{#elif} can go in the same conditional group. Then 2937the text after each @samp{#elif} is processed only if the @samp{#elif} 2938condition succeeds after the original @samp{#if} and all previous 2939@samp{#elif} directives within it have failed. 2940 2941@samp{#else} is allowed after any number of @samp{#elif} directives, but 2942@samp{#elif} may not follow @samp{#else}. 2943 2944@node Deleted Code 2945@section Deleted Code 2946@cindex commenting out code 2947 2948If you replace or delete a part of the program but want to keep the old 2949code around for future reference, you often cannot simply comment it 2950out. Block comments do not nest, so the first comment inside the old 2951code will end the commenting-out. The probable result is a flood of 2952syntax errors. 2953 2954One way to avoid this problem is to use an always-false conditional 2955instead. For instance, put @code{#if 0} before the deleted code and 2956@code{#endif} after it. This works even if the code being turned 2957off contains conditionals, but they must be entire conditionals 2958(balanced @samp{#if} and @samp{#endif}). 2959 2960Some people use @code{#ifdef notdef} instead. This is risky, because 2961@code{notdef} might be accidentally defined as a macro, and then the 2962conditional would succeed. @code{#if 0} can be counted on to fail. 2963 2964Do not use @code{#if 0} for comments which are not C code. Use a real 2965comment, instead. The interior of @code{#if 0} must consist of complete 2966tokens; in particular, single-quote characters must balance. Comments 2967often contain unbalanced single-quote characters (known in English as 2968apostrophes). These confuse @code{#if 0}. They don't confuse 2969@samp{/*}. 2970 2971@node Diagnostics 2972@chapter Diagnostics 2973@cindex diagnostic 2974@cindex reporting errors 2975@cindex reporting warnings 2976 2977@findex #error 2978The directive @samp{#error} causes the preprocessor to report a fatal 2979error. The tokens forming the rest of the line following @samp{#error} 2980are used as the error message. 2981 2982You would use @samp{#error} inside of a conditional that detects a 2983combination of parameters which you know the program does not properly 2984support. For example, if you know that the program will not run 2985properly on a VAX, you might write 2986 2987@example 2988@group 2989#ifdef __vax__ 2990#error "Won't work on VAXen. See comments at get_last_object." 2991#endif 2992@end group 2993@end example 2994 2995If you have several configuration parameters that must be set up by 2996the installation in a consistent way, you can use conditionals to detect 2997an inconsistency and report it with @samp{#error}. For example, 2998 2999@example 3000#if !defined(UNALIGNED_INT_ASM_OP) && defined(DWARF2_DEBUGGING_INFO) 3001#error "DWARF2_DEBUGGING_INFO requires UNALIGNED_INT_ASM_OP." 3002#endif 3003@end example 3004 3005@findex #warning 3006The directive @samp{#warning} is like @samp{#error}, but causes the 3007preprocessor to issue a warning and continue preprocessing. The tokens 3008following @samp{#warning} are used as the warning message. 3009 3010You might use @samp{#warning} in obsolete header files, with a message 3011directing the user to the header file which should be used instead. 3012 3013Neither @samp{#error} nor @samp{#warning} macro-expands its argument. 3014Internal whitespace sequences are each replaced with a single space. 3015The line must consist of complete tokens. It is wisest to make the 3016argument of these directives be a single string constant; this avoids 3017problems with apostrophes and the like. 3018 3019@node Line Control 3020@chapter Line Control 3021@cindex line control 3022 3023The C preprocessor informs the C compiler of the location in your source 3024code where each token came from. Presently, this is just the file name 3025and line number. All the tokens resulting from macro expansion are 3026reported as having appeared on the line of the source file where the 3027outermost macro was used. We intend to be more accurate in the future. 3028 3029If you write a program which generates source code, such as the 3030@command{bison} parser generator, you may want to adjust the preprocessor's 3031notion of the current file name and line number by hand. Parts of the 3032output from @command{bison} are generated from scratch, other parts come 3033from a standard parser file. The rest are copied verbatim from 3034@command{bison}'s input. You would like compiler error messages and 3035symbolic debuggers to be able to refer to @code{bison}'s input file. 3036 3037@findex #line 3038@command{bison} or any such program can arrange this by writing 3039@samp{#line} directives into the output file. @samp{#line} is a 3040directive that specifies the original line number and source file name 3041for subsequent input in the current preprocessor input file. 3042@samp{#line} has three variants: 3043 3044@table @code 3045@item #line @var{linenum} 3046@var{linenum} is a non-negative decimal integer constant. It specifies 3047the line number which should be reported for the following line of 3048input. Subsequent lines are counted from @var{linenum}. 3049 3050@item #line @var{linenum} @var{filename} 3051@var{linenum} is the same as for the first form, and has the same 3052effect. In addition, @var{filename} is a string constant. The 3053following line and all subsequent lines are reported to come from the 3054file it specifies, until something else happens to change that. 3055@var{filename} is interpreted according to the normal rules for a string 3056constant: backslash escapes are interpreted. This is different from 3057@samp{#include}. 3058 3059Previous versions of GNU CPP did not interpret escapes in @samp{#line}; 3060we have changed it because the standard requires they be interpreted, 3061and most other compilers do. 3062 3063@item #line @var{anything else} 3064@var{anything else} is checked for macro calls, which are expanded. 3065The result should match one of the above two forms. 3066@end table 3067 3068@samp{#line} directives alter the results of the @code{__FILE__} and 3069@code{__LINE__} predefined macros from that point on. @xref{Standard 3070Predefined Macros}. They do not have any effect on @samp{#include}'s 3071idea of the directory containing the current file. This is a change 3072from GCC 2.95. Previously, a file reading 3073 3074@smallexample 3075#line 1 "../src/gram.y" 3076#include "gram.h" 3077@end smallexample 3078 3079would search for @file{gram.h} in @file{../src}, then the @option{-I} 3080chain; the directory containing the physical source file would not be 3081searched. In GCC 3.0 and later, the @samp{#include} is not affected by 3082the presence of a @samp{#line} referring to a different directory. 3083 3084We made this change because the old behavior caused problems when 3085generated source files were transported between machines. For instance, 3086it is common practice to ship generated parsers with a source release, 3087so that people building the distribution do not need to have yacc or 3088Bison installed. These files frequently have @samp{#line} directives 3089referring to the directory tree of the system where the distribution was 3090created. If GCC tries to search for headers in those directories, the 3091build is likely to fail. 3092 3093The new behavior can cause failures too, if the generated file is not 3094in the same directory as its source and it attempts to include a header 3095which would be visible searching from the directory containing the 3096source file. However, this problem is easily solved with an additional 3097@option{-I} switch on the command line. The failures caused by the old 3098semantics could sometimes be corrected only by editing the generated 3099files, which is difficult and error-prone. 3100 3101@node Pragmas 3102@chapter Pragmas 3103 3104The @samp{#pragma} directive is the method specified by the C standard 3105for providing additional information to the compiler, beyond what is 3106conveyed in the language itself. Three forms of this directive 3107(commonly known as @dfn{pragmas}) are specified by the 1999 C standard. 3108A C compiler is free to attach any meaning it likes to other pragmas. 3109 3110GCC has historically preferred to use extensions to the syntax of the 3111language, such as @code{__attribute__}, for this purpose. However, GCC 3112does define a few pragmas of its own. These mostly have effects on the 3113entire translation unit or source file. 3114 3115In GCC version 3, all GNU-defined, supported pragmas have been given a 3116@code{GCC} prefix. This is in line with the @code{STDC} prefix on all 3117pragmas defined by C99. For backward compatibility, pragmas which were 3118recognized by previous versions are still recognized without the 3119@code{GCC} prefix, but that usage is deprecated. Some older pragmas are 3120deprecated in their entirety. They are not recognized with the 3121@code{GCC} prefix. @xref{Obsolete Features}. 3122 3123@cindex @code{_Pragma} 3124C99 introduces the @code{@w{_Pragma}} operator. This feature addresses a 3125major problem with @samp{#pragma}: being a directive, it cannot be 3126produced as the result of macro expansion. @code{@w{_Pragma}} is an 3127operator, much like @code{sizeof} or @code{defined}, and can be embedded 3128in a macro. 3129 3130Its syntax is @code{@w{_Pragma (@var{string-literal})}}, where 3131@var{string-literal} can be either a normal or wide-character string 3132literal. It is destringized, by replacing all @samp{\\} with a single 3133@samp{\} and all @samp{\"} with a @samp{"}. The result is then 3134processed as if it had appeared as the right hand side of a 3135@samp{#pragma} directive. For example, 3136 3137@example 3138_Pragma ("GCC dependency \"parse.y\"") 3139@end example 3140 3141@noindent 3142has the same effect as @code{#pragma GCC dependency "parse.y"}. The 3143same effect could be achieved using macros, for example 3144 3145@example 3146#define DO_PRAGMA(x) _Pragma (#x) 3147DO_PRAGMA (GCC dependency "parse.y") 3148@end example 3149 3150The standard is unclear on where a @code{_Pragma} operator can appear. 3151The preprocessor does not accept it within a preprocessing conditional 3152directive like @samp{#if}. To be safe, you are probably best keeping it 3153out of directives other than @samp{#define}, and putting it on a line of 3154its own. 3155 3156This manual documents the pragmas which are meaningful to the 3157preprocessor itself. Other pragmas are meaningful to the C or C++ 3158compilers. They are documented in the GCC manual. 3159 3160@ftable @code 3161@item #pragma GCC dependency 3162@code{#pragma GCC dependency} allows you to check the relative dates of 3163the current file and another file. If the other file is more recent than 3164the current file, a warning is issued. This is useful if the current 3165file is derived from the other file, and should be regenerated. The 3166other file is searched for using the normal include search path. 3167Optional trailing text can be used to give more information in the 3168warning message. 3169 3170@example 3171#pragma GCC dependency "parse.y" 3172#pragma GCC dependency "/usr/include/time.h" rerun fixincludes 3173@end example 3174 3175@item #pragma GCC poison 3176Sometimes, there is an identifier that you want to remove completely 3177from your program, and make sure that it never creeps back in. To 3178enforce this, you can @dfn{poison} the identifier with this pragma. 3179@code{#pragma GCC poison} is followed by a list of identifiers to 3180poison. If any of those identifiers appears anywhere in the source 3181after the directive, it is a hard error. For example, 3182 3183@example 3184#pragma GCC poison printf sprintf fprintf 3185sprintf(some_string, "hello"); 3186@end example 3187 3188@noindent 3189will produce an error. 3190 3191If a poisoned identifier appears as part of the expansion of a macro 3192which was defined before the identifier was poisoned, it will @emph{not} 3193cause an error. This lets you poison an identifier without worrying 3194about system headers defining macros that use it. 3195 3196For example, 3197 3198@example 3199#define strrchr rindex 3200#pragma GCC poison rindex 3201strrchr(some_string, 'h'); 3202@end example 3203 3204@noindent 3205will not produce an error. 3206 3207@item #pragma GCC system_header 3208This pragma takes no arguments. It causes the rest of the code in the 3209current file to be treated as if it came from a system header. 3210@xref{System Headers}. 3211 3212@end ftable 3213 3214@node Other Directives 3215@chapter Other Directives 3216 3217@findex #ident 3218The @samp{#ident} directive takes one argument, a string constant. On 3219some systems, that string constant is copied into a special segment of 3220the object file. On other systems, the directive is ignored. 3221 3222This directive is not part of the C standard, but it is not an official 3223GNU extension either. We believe it came from System V@. 3224 3225@findex #sccs 3226The @samp{#sccs} directive is recognized on some systems, because it 3227appears in their header files. It is a very old, obscure, extension 3228which we did not invent, and we have been unable to find any 3229documentation of what it should do, so GCC simply ignores it. 3230 3231@cindex null directive 3232The @dfn{null directive} consists of a @samp{#} followed by a newline, 3233with only whitespace (including comments) in between. A null directive 3234is understood as a preprocessing directive but has no effect on the 3235preprocessor output. The primary significance of the existence of the 3236null directive is that an input line consisting of just a @samp{#} will 3237produce no output, rather than a line of output containing just a 3238@samp{#}. Supposedly some old C programs contain such lines. 3239 3240@node Preprocessor Output 3241@chapter Preprocessor Output 3242 3243When the C preprocessor is used with the C, C++, or Objective-C 3244compilers, it is integrated into the compiler and communicates a stream 3245of binary tokens directly to the compiler's parser. However, it can 3246also be used in the more conventional standalone mode, where it produces 3247textual output. 3248@c FIXME: Document the library interface. 3249 3250@cindex output format 3251The output from the C preprocessor looks much like the input, except 3252that all preprocessing directive lines have been replaced with blank 3253lines and all comments with spaces. Long runs of blank lines are 3254discarded. 3255 3256The ISO standard specifies that it is implementation defined whether a 3257preprocessor preserves whitespace between tokens, or replaces it with 3258e.g.@: a single space. In GNU CPP, whitespace between tokens is collapsed 3259to become a single space, with the exception that the first token on a 3260non-directive line is preceded with sufficient spaces that it appears in 3261the same column in the preprocessed output that it appeared in the 3262original source file. This is so the output is easy to read. 3263@xref{Differences from previous versions}. CPP does not insert any 3264whitespace where there was none in the original source, except where 3265necessary to prevent an accidental token paste. 3266 3267@cindex linemarkers 3268Source file name and line number information is conveyed by lines 3269of the form 3270 3271@example 3272# @var{linenum} @var{filename} @var{flags} 3273@end example 3274 3275@noindent 3276These are called @dfn{linemarkers}. They are inserted as needed into 3277the output (but never within a string or character constant). They mean 3278that the following line originated in file @var{filename} at line 3279@var{linenum}. @var{filename} will never contain any non-printing 3280characters; they are replaced with octal escape sequences. 3281 3282After the file name comes zero or more flags, which are @samp{1}, 3283@samp{2}, @samp{3}, or @samp{4}. If there are multiple flags, spaces 3284separate them. Here is what the flags mean: 3285 3286@table @samp 3287@item 1 3288This indicates the start of a new file. 3289@item 2 3290This indicates returning to a file (after having included another file). 3291@item 3 3292This indicates that the following text comes from a system header file, 3293so certain warnings should be suppressed. 3294@item 4 3295This indicates that the following text should be treated as being 3296wrapped in an implicit @code{extern "C"} block. 3297@c maybe cross reference NO_IMPLICIT_EXTERN_C 3298@end table 3299 3300As an extension, the preprocessor accepts linemarkers in non-assembler 3301input files. They are treated like the corresponding @samp{#line} 3302directive, (@pxref{Line Control}), except that trailing flags are 3303permitted, and are interpreted with the meanings described above. If 3304multiple flags are given, they must be in ascending order. 3305 3306Some directives may be duplicated in the output of the preprocessor. 3307These are @samp{#ident} (always), @samp{#pragma} (only if the 3308preprocessor does not handle the pragma itself), and @samp{#define} and 3309@samp{#undef} (with certain debugging options). If this happens, the 3310@samp{#} of the directive will always be in the first column, and there 3311will be no space between the @samp{#} and the directive name. If macro 3312expansion happens to generate tokens which might be mistaken for a 3313duplicated directive, a space will be inserted between the @samp{#} and 3314the directive name. 3315 3316@node Traditional Mode 3317@chapter Traditional Mode 3318 3319Traditional (pre-standard) C preprocessing is rather different from 3320the preprocessing specified by the standard. When GCC is given the 3321@option{-traditional} option, it attempts to emulate a traditional 3322preprocessor. We do not guarantee that GCC's behavior under 3323@option{-traditional} matches any pre-standard preprocessor exactly. 3324 3325Traditional mode exists only for backward compatibility. We have no 3326plans to augment it in any way nor will we change it except to fix 3327catastrophic bugs. You should be aware that modern C libraries often 3328have header files which are incompatible with traditional mode. 3329 3330This is a list of the differences. It may not be complete, and may not 3331correspond exactly to the behavior of either GCC or a true traditional 3332preprocessor. 3333 3334@itemize @bullet 3335@item 3336Traditional macro expansion pays no attention to single-quote or 3337double-quote characters; macro argument symbols are replaced by the 3338argument values even when they appear within apparent string or 3339character constants. 3340 3341@item 3342Traditionally, it is permissible for a macro expansion to end in the 3343middle of a string or character constant. The constant continues into 3344the text surrounding the macro call. 3345 3346@item 3347However, the end of the line terminates a string or character constant, 3348with no error. (This is a kluge. Traditional mode is commonly used to 3349preprocess things which are not C, and have a different comment syntax. 3350Single apostrophes often appear in comments. This kluge prevents the 3351traditional preprocessor from issuing errors on such comments.) 3352 3353@item 3354Preprocessing directives are recognized in traditional C only when their 3355leading @samp{#} appears in the first column. There can be no 3356whitespace between the beginning of the line and the @samp{#}. 3357 3358@item 3359In traditional C, a comment is equivalent to no text at all. (In ISO 3360C, a comment counts as whitespace.) It can be used sort of the same way 3361that @samp{##} is used in ISO C, to paste macro arguments together. 3362 3363@item 3364Traditional C does not have the concept of a preprocessing number. 3365 3366@item 3367A macro is not suppressed within its own definition, in traditional C@. 3368Thus, any macro that is used recursively inevitably causes an error. 3369 3370@item 3371The @samp{#} and @samp{##} operators are not available in traditional 3372C@. 3373 3374@item 3375In traditional C, the text at the end of a macro expansion can run 3376together with the text after the macro call, to produce a single token. 3377This is impossible in ISO C@. 3378 3379@item 3380None of the GNU extensions to the preprocessor are available in 3381traditional mode, with the exception of a partial implementation of 3382assertions, and those may be removed in the future. 3383 3384@item 3385A true traditional C preprocessor does not recognize @samp{#elif}, 3386@samp{#error}, or @samp{#pragma}. GCC supports @samp{#elif} and 3387@samp{#error} even in traditional mode, but not @samp{#pragma}. 3388 3389@item 3390Traditional mode is text-based, not token-based, and comments are 3391stripped after macro expansion. Therefore, @samp{/**/} can be used to 3392paste tokens together provided that there is no whitespace between it 3393and the tokens to be pasted. 3394 3395@item 3396Traditional mode preserves the amount and form of whitespace provided by 3397the user. Hard tabs remain hard tabs. This can be useful, e.g.@: if you 3398are preprocessing a Makefile (which we do not encourage). 3399@end itemize 3400 3401You can request warnings about features that did not exist, or worked 3402differently, in traditional C with the @option{-Wtraditional} option. 3403This works only if you do @emph{not} specify @option{-traditional}. GCC 3404does not warn about features of ISO C which you must use when you are 3405using a conforming compiler, such as the @samp{#} and @samp{##} 3406operators. 3407 3408Presently @option{-Wtraditional} warns about: 3409 3410@itemize @bullet 3411@item 3412Macro parameters that appear within string literals in the macro body. 3413In traditional C macro replacement takes place within string literals, 3414but does not in ISO C@. 3415 3416@item 3417In traditional C, some preprocessor directives did not exist. 3418Traditional preprocessors would only consider a line to be a directive 3419if the @samp{#} appeared in column 1 on the line. Therefore 3420@option{-Wtraditional} warns about directives that traditional C 3421understands but would ignore because the @samp{#} does not appear as the 3422first character on the line. It also suggests you hide directives like 3423@samp{#pragma} not understood by traditional C by indenting them. Some 3424traditional implementations would not recognize @samp{#elif}, so it 3425suggests avoiding it altogether. 3426 3427@item 3428A function-like macro that appears without an argument list. In 3429traditional C this was an error. In ISO C it merely means that the 3430macro is not expanded. 3431 3432@item 3433The unary plus operator. This did not exist in traditional C@. 3434 3435@item 3436The @samp{U} and @samp{LL} integer constant suffixes, which were not 3437available in traditional C@. (Traditional C does support the @samp{L} 3438suffix for simple long integer constants.) You are not warned about 3439uses of these suffixes in macros defined in system headers. For 3440instance, @code{UINT_MAX} may well be defined as @code{4294967295U}, but 3441you will not be warned if you use @code{UINT_MAX}. 3442 3443You can usually avoid the warning, and the related warning about 3444constants which are so large that they are unsigned, by writing the 3445integer constant in question in hexadecimal, with no U suffix. Take 3446care, though, because this gives the wrong result in exotic cases. 3447@end itemize 3448 3449@node Implementation Details 3450@chapter Implementation Details 3451 3452Here we document details of how the preprocessor's implementation 3453affects its user-visible behavior. You should try to avoid undue 3454reliance on behavior described here, as it is possible that it will 3455change subtly in future implementations. 3456 3457Also documented here are obsolete features and changes from previous 3458versions of GNU CPP@. 3459 3460@menu 3461* Implementation-defined behavior:: 3462* Implementation limits:: 3463* Obsolete Features:: 3464* Differences from previous versions:: 3465@end menu 3466 3467@node Implementation-defined behavior 3468@section Implementation-defined behavior 3469@cindex implementation-defined behavior 3470 3471This is how GNU CPP behaves in all the cases which the C standard 3472describes as @dfn{implementation-defined}. This term means that the 3473implementation is free to do what it likes, but must document its choice 3474and stick to it. 3475@c FIXME: Check the C++ standard for more implementation-defined stuff. 3476 3477@itemize @bullet 3478@need 1000 3479@item The mapping of physical source file multi-byte characters to the 3480execution character set. 3481 3482Currently, GNU cpp only supports character sets that are strict supersets 3483of ASCII, and performs no translation of characters. 3484 3485@item Non-empty sequences of whitespace characters. 3486 3487In textual output, each whitespace sequence is collapsed to a single 3488space. For aesthetic reasons, the first token on each non-directive 3489line of output is preceded with sufficient spaces that it appears in the 3490same column as it did in the original source file. 3491 3492@item The numeric value of character constants in preprocessor expressions. 3493 3494The preprocessor and compiler interpret character constants in the same 3495way; escape sequences such as @samp{\a} are given the values they would 3496have on the target machine. 3497 3498Multi-character character constants are interpreted a character at a 3499time, shifting the previous result left by the number of bits per 3500character on the host, and adding the new character. For example, 'ab' 3501on an 8-bit host would be interpreted as @w{'a' * 256 + 'b'}. If there 3502are more characters in the constant than can fit in the widest native 3503integer type on the host, usually a @code{long}, the excess characters 3504are ignored and a diagnostic is given. 3505 3506@item Source file inclusion. 3507 3508For a discussion on how the preprocessor locates header files, 3509@ref{Include Operation}. 3510 3511@item Interpretation of the filename resulting from a macro-expanded 3512@samp{#include} directive. 3513 3514@xref{Computed Includes}. 3515 3516@item Treatment of a @samp{#pragma} directive that after macro-expansion 3517results in a standard pragma. 3518 3519No macro expansion occurs on any @samp{#pragma} directive line, so the 3520question does not arise. 3521 3522Note that GCC does not yet implement any of the standard 3523pragmas. 3524 3525@end itemize 3526 3527@node Implementation limits 3528@section Implementation limits 3529@cindex implementation limits 3530 3531GNU CPP has a small number of internal limits. This section lists the 3532limits which the C standard requires to be no lower than some minimum, 3533and all the others we are aware of. We intend there to be as few limits 3534as possible. If you encounter an undocumented or inconvenient limit, 3535please report that to us as a bug. (See the section on reporting bugs in 3536the GCC manual.) 3537 3538Where we say something is limited @dfn{only by available memory}, that 3539means that internal data structures impose no intrinsic limit, and space 3540is allocated with @code{malloc} or equivalent. The actual limit will 3541therefore depend on many things, such as the size of other things 3542allocated by the compiler at the same time, the amount of memory 3543consumed by other processes on the same computer, etc. 3544 3545@itemize @bullet 3546 3547@item Nesting levels of @samp{#include} files. 3548 3549We impose an arbitrary limit of 200 levels, to avoid runaway recursion. 3550The standard requires at least 15 levels. 3551 3552@item Nesting levels of conditional inclusion. 3553 3554The C standard mandates this be at least 63. GNU CPP is limited only by 3555available memory. 3556 3557@item Levels of parenthesised expressions within a full expression. 3558 3559The C standard requires this to be at least 63. In preprocessor 3560conditional expressions, it is limited only by available memory. 3561 3562@item Significant initial characters in an identifier or macro name. 3563 3564The preprocessor treats all characters as significant. The C standard 3565requires only that the first 63 be significant. 3566 3567@item Number of macros simultaneously defined in a single translation unit. 3568 3569The standard requires at least 4095 be possible. GNU CPP is limited only 3570by available memory. 3571 3572@item Number of parameters in a macro definition and arguments in a macro call. 3573 3574We allow @code{USHRT_MAX}, which is no smaller than 65,535. The minimum 3575required by the standard is 127. 3576 3577@item Number of characters on a logical source line. 3578 3579The C standard requires a minimum of 4096 be permitted. GNU CPP places 3580no limits on this, but you may get incorrect column numbers reported in 3581diagnostics for lines longer than 65,535 characters. 3582 3583@item Maximum size of a source file. 3584 3585The standard does not specify any lower limit on the maximum size of a 3586source file. GNU cpp maps files into memory, so it is limited by the 3587available address space. This is generally at least two gigabytes. 3588Depending on the operating system, the size of physical memory may or 3589may not be a limitation. 3590 3591@end itemize 3592 3593@node Obsolete Features 3594@section Obsolete Features 3595 3596GNU CPP has a number of features which are present mainly for 3597compatibility with older programs. We discourage their use in new code. 3598In some cases, we plan to remove the feature in a future version of GCC@. 3599 3600@menu 3601* Assertions:: 3602* Obsolete once-only headers:: 3603* Miscellaneous obsolete features:: 3604@end menu 3605 3606@node Assertions 3607@subsection Assertions 3608@cindex assertions 3609 3610@dfn{Assertions} are a deprecated alternative to macros in writing 3611conditionals to test what sort of computer or system the compiled 3612program will run on. Assertions are usually predefined, but you can 3613define them with preprocessing directives or command-line options. 3614 3615Assertions were intended to provide a more systematic way to describe 3616the compiler's target system. However, in practice they are just as 3617unpredictable as the system-specific predefined macros. In addition, they 3618are not part of any standard, and only a few compilers support them. 3619Therefore, the use of assertions is @strong{less} portable than the use 3620of system-specific predefined macros. We recommend you do not use them at 3621all. 3622 3623@cindex predicates 3624An assertion looks like this: 3625 3626@example 3627#@var{predicate} (@var{answer}) 3628@end example 3629 3630@noindent 3631@var{predicate} must be a single identifier. @var{answer} can be any 3632sequence of tokens; all characters are significant except for leading 3633and trailing whitespace, and differences in internal whitespace 3634sequences are ignored. (This is similar to the rules governing macro 3635redefinition.) Thus, @code{(x + y)} is different from @code{(x+y)} but 3636equivalent to @code{@w{( x + y )}}. Parentheses do not nest inside an 3637answer. 3638 3639@cindex testing predicates 3640To test an assertion, you write it in an @samp{#if}. For example, this 3641conditional succeeds if either @code{vax} or @code{ns16000} has been 3642asserted as an answer for @code{machine}. 3643 3644@example 3645#if #machine (vax) || #machine (ns16000) 3646@end example 3647 3648@noindent 3649You can test whether @emph{any} answer is asserted for a predicate by 3650omitting the answer in the conditional: 3651 3652@example 3653#if #machine 3654@end example 3655 3656@findex #assert 3657Assertions are made with the @samp{#assert} directive. Its sole 3658argument is the assertion to make, without the leading @samp{#} that 3659identifies assertions in conditionals. 3660 3661@example 3662#assert @var{predicate} (@var{answer}) 3663@end example 3664 3665@noindent 3666You may make several assertions with the same predicate and different 3667answers. Subsequent assertions do not override previous ones for the 3668same predicate. All the answers for any given predicate are 3669simultaneously true. 3670 3671@cindex assertions, cancelling 3672@findex #unassert 3673Assertions can be cancelled with the @samp{#unassert} directive. It 3674has the same syntax as @samp{#assert}. In that form it cancels only the 3675answer which was specified on the @samp{#unassert} line; other answers 3676for that predicate remain true. You can cancel an entire predicate by 3677leaving out the answer: 3678 3679@example 3680#unassert @var{predicate} 3681@end example 3682 3683@noindent 3684In either form, if no such assertion has been made, @samp{#unassert} has 3685no effect. 3686 3687You can also make or cancel assertions using command line options. 3688@xref{Invocation}. 3689 3690@node Obsolete once-only headers 3691@subsection Obsolete once-only headers 3692 3693GNU CPP supports two more ways of indicating that a header file should be 3694read only once. Neither one is as portable as a wrapper @samp{#ifndef}, 3695and we recommend you do not use them in new programs. 3696 3697@findex #import 3698In the Objective-C language, there is a variant of @samp{#include} 3699called @samp{#import} which includes a file, but does so at most once. 3700If you use @samp{#import} instead of @samp{#include}, then you don't 3701need the conditionals inside the header file to prevent multiple 3702inclusion of the contents. GCC permits the use of @samp{#import} in C 3703and C++ as well as Objective-C@. However, it is not in standard C or C++ 3704and should therefore not be used by portable programs. 3705 3706@samp{#import} is not a well designed feature. It requires the users of 3707a header file to know that it should only be included once. It is much 3708better for the header file's implementor to write the file so that users 3709don't need to know this. Using a wrapper @samp{#ifndef} accomplishes 3710this goal. 3711 3712In the present implementation, a single use of @samp{#import} will 3713prevent the file from ever being read again, by either @samp{#import} or 3714@samp{#include}. You should not rely on this; do not use both 3715@samp{#import} and @samp{#include} to refer to the same header file. 3716 3717Another way to prevent a header file from being included more than once 3718is with the @samp{#pragma once} directive. If @samp{#pragma once} is 3719seen when scanning a header file, that file will never be read again, no 3720matter what. 3721 3722@samp{#pragma once} does not have the problems that @samp{#import} does, 3723but it is not recognized by all preprocessors, so you cannot rely on it 3724in a portable program. 3725 3726@node Miscellaneous obsolete features 3727@subsection Miscellaneous obsolete features 3728 3729Here are a few more obsolete features. 3730 3731@itemize @bullet 3732@cindex invalid token paste 3733@item Attempting to paste two tokens which together do not form a valid 3734preprocessing token. 3735 3736The preprocessor currently warns about this and outputs the two tokens 3737adjacently, which is probably the behavior the programmer intends. It 3738may not work in future, though. 3739 3740Most of the time, when you get this warning, you will find that @samp{##} 3741is being used superstitiously, to guard against whitespace appearing 3742between two tokens. It is almost always safe to delete the @samp{##}. 3743 3744@cindex pragma poison 3745@item @code{#pragma poison} 3746 3747This is the same as @code{#pragma GCC poison}. The version without the 3748@code{GCC} prefix is deprecated. @xref{Pragmas}. 3749 3750@cindex multi-line string constants 3751@item Multi-line string constants 3752 3753GCC currently allows a string constant to extend across multiple logical 3754lines of the source file. This extension is deprecated and will be 3755removed in a future version of GCC@. Such string constants are already 3756rejected in all directives apart from @samp{#define}. 3757 3758Instead, make use of ISO C concatenation of adjacent string literals, or 3759use @samp{\n} followed by a backslash-newline. 3760 3761@end itemize 3762 3763@node Differences from previous versions 3764@section Differences from previous versions 3765@cindex differences from previous versions 3766 3767This section details behavior which has changed from previous versions 3768of GNU CPP@. We do not plan to change it again in the near future, but 3769we do not promise not to, either. 3770 3771The ``previous versions'' discussed here are 2.95 and before. The 3772behavior of GCC 3.0 is mostly the same as the behavior of the widely 3773used 2.96 and 2.97 development snapshots. Where there are differences, 3774they generally represent bugs in the snapshots. 3775 3776@itemize @bullet 3777 3778@item Order of evaluation of @samp{#} and @samp{##} operators 3779 3780The standard does not specify the order of evaluation of a chain of 3781@samp{##} operators, nor whether @samp{#} is evaluated before, after, or 3782at the same time as @samp{##}. You should therefore not write any code 3783which depends on any specific ordering. It is possible to guarantee an 3784ordering, if you need one, by suitable use of nested macros. 3785 3786An example of where this might matter is pasting the arguments @samp{1}, 3787@samp{e} and @samp{-2}. This would be fine for left-to-right pasting, 3788but right-to-left pasting would produce an invalid token @samp{e-2}. 3789 3790GCC 3.0 evaluates @samp{#} and @samp{##} at the same time and strictly 3791left to right. Older versions evaluated all @samp{#} operators first, 3792then all @samp{##} operators, in an unreliable order. 3793 3794@item The form of whitespace betwen tokens in preprocessor output 3795 3796@xref{Preprocessor Output}, for the current textual format. This is 3797also the format used by stringification. Normally, the preprocessor 3798communicates tokens directly to the compiler's parser, and whitespace 3799does not come up at all. 3800 3801Older versions of GCC preserved all whitespace provided by the user and 3802inserted lots more whitespace of their own, because they could not 3803accurately predict when extra spaces were needed to prevent accidental 3804token pasting. 3805 3806@item Optional argument when invoking rest argument macros 3807 3808As an extension, GCC permits you to omit the variable arguments entirely 3809when you use a variable argument macro. This is forbidden by the 1999 C 3810standard, and will provoke a pedantic warning with GCC 3.0. Previous 3811versions accepted it silently. 3812 3813@item @samp{##} swallowing preceding text in rest argument macros 3814 3815Formerly, in a macro expansion, if @samp{##} appeared before a variable 3816arguments parameter, and the set of tokens specified for that argument 3817in the macro invocation was empty, previous versions of GNU CPP would 3818back up and remove the preceding sequence of non-whitespace characters 3819(@strong{not} the preceding token). This extension is in direct 3820conflict with the 1999 C standard and has been drastically pared back. 3821 3822In the current version of the preprocessor, if @samp{##} appears between 3823a comma and a variable arguments parameter, and the variable argument is 3824omitted entirely, the comma will be removed from the expansion. If the 3825variable argument is empty, or the token before @samp{##} is not a 3826comma, then @samp{##} behaves as a normal token paste. 3827 3828@item Traditional mode and GNU extensions 3829 3830Traditional mode used to be implemented in the same program as normal 3831preprocessing. Therefore, all the GNU extensions to the preprocessor 3832were still available in traditional mode. It is now a separate program 3833and does not implement any of the GNU extensions, except for a partial 3834implementation of assertions. Even those may be removed in a future 3835release. 3836 3837@item @samp{#line} and @samp{#include} 3838 3839The @samp{#line} directive used to change GCC's notion of the 3840``directory containing the current file,'' used by @samp{#include} with 3841a double-quoted header file name. In 3.0 and later, it does not. 3842@xref{Line Control}, for further explanation. 3843 3844@item Syntax of @samp{#line} 3845 3846In GCC 2.95 and previous, the string constant argument to @samp{#line} 3847was treated the same way as the argument to @samp{#include}: backslash 3848escapes were not honored, and the string ended at the second @samp{"}. 3849This is not compliant with the C standard. In GCC 3.0, an attempt was 3850made to correct the behavior, so that the string was treated as a real 3851string constant, but it turned out to be buggy. In 3.1, the bugs have 3852been fixed. (We are not fixing the bugs in 3.0 because they affect 3853relatively few people and the fix is quite invasive.) 3854 3855@end itemize 3856 3857@node Invocation 3858@chapter Invocation 3859@cindex invocation 3860@cindex command line 3861 3862Most often when you use the C preprocessor you will not have to invoke it 3863explicitly: the C compiler will do so automatically. However, the 3864preprocessor is sometimes useful on its own. All the options listed 3865here are also acceptable to the C compiler and have the same meaning, 3866except that the C compiler has different rules for specifying the output 3867file. 3868 3869@strong{Note:} Whether you use the preprocessor by way of @command{gcc} 3870or @command{cpp}, the @dfn{compiler driver} is run first. This 3871program's purpose is to translate your command into invocations of the 3872programs that do the actual work. Their command line interfaces are 3873similar but not identical to the documented interface, and may change 3874without notice. 3875 3876@ignore 3877@c man begin SYNOPSIS 3878cpp [@option{-D}@var{macro}[=@var{defn}]@dots{}] [@option{-U}@var{macro}] 3879 [@option{-I}@var{dir}@dots{}] [@option{-W}@var{warn}@dots{}] 3880 [@option{-M}|@option{-MM}] [@option{-MG}] [@option{-MF} @var{filename}] 3881 [@option{-MP}] [@option{-MQ} @var{target}@dots{}] [@option{-MT} @var{target}@dots{}] 3882 [@option{-x} @var{language}] [@option{-std=}@var{standard}] 3883 @var{infile} @var{outfile} 3884 3885Only the most useful options are listed here; see below for the remainder. 3886@c man end 3887@c man begin SEEALSO 3888gpl(7), gfdl(7), fsf-funding(7), 3889gcc(1), as(1), ld(1), and the Info entries for @file{cpp}, @file{gcc}, and 3890@file{binutils}. 3891@c man end 3892@end ignore 3893 3894@c man begin OPTIONS 3895The C preprocessor expects two file names as arguments, @var{infile} and 3896@var{outfile}. The preprocessor reads @var{infile} together with any 3897other files it specifies with @samp{#include}. All the output generated 3898by the combined input files is written in @var{outfile}. 3899 3900Either @var{infile} or @var{outfile} may be @option{-}, which as 3901@var{infile} means to read from standard input and as @var{outfile} 3902means to write to standard output. Also, if either file is omitted, it 3903means the same as if @option{-} had been specified for that file. 3904 3905Unless otherwise noted, or the option ends in @samp{=}, all options 3906which take an argument may have that argument appear either immediately 3907after the option, or with a space between option and argument: 3908@option{-Ifoo} and @option{-I foo} have the same effect. 3909 3910@cindex grouping options 3911@cindex options, grouping 3912Many options have multi-letter names; therefore multiple single-letter 3913options may @emph{not} be grouped: @option{-dM} is very different from 3914@w{@samp{-d -M}}. 3915 3916@cindex options 3917@include cppopts.texi 3918@c man end 3919 3920@node Environment Variables 3921@chapter Environment Variables 3922@cindex environment variables 3923@c man begin ENVIRONMENT 3924 3925This section describes the environment variables that affect how CPP 3926operates. You can use them to specify directories or prefixes to use 3927when searching for include files, or to control dependency output. 3928 3929Note that you can also specify places to search using options such as 3930@option{-I}, and control dependency output with options like 3931@option{-M} (@pxref{Invocation}). These take precedence over 3932environment variables, which in turn take precedence over the 3933configuration of GCC@. 3934 3935@include cppenv.texi 3936@c man end 3937 3938@include fdl.texi 3939 3940@page 3941@node Option Index 3942@unnumbered Option Index 3943 3944CPP's command line options are indexed here without any initial 3945@samp{-} or @samp{--}. 3946 3947@printindex op 3948 3949@node Index of Directives 3950@unnumbered Index of Directives 3951@printindex fn 3952 3953@node Concept Index 3954@unnumbered Concept Index 3955@printindex cp 3956 3957@bye 3958