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. The only 834exception is when @file{dir} is already searched by default. In 835this case, the option is ignored and the search order for system 836directories remains unchanged. 837 838Duplicate directories are removed from the quote and bracket search 839chains before the two chains are merged to make the final search chain. 840Thus, it is possible for a directory to occur twice in the final search 841chain if it was specified in both the quote and bracket chains. 842 843You can prevent GCC from searching any of the default directories with 844the @option{-nostdinc} option. This is useful when you are compiling an 845operating system kernel or some other program that does not use the 846standard C library facilities, or the standard C library itself. 847@option{-I} options are not ignored as described above when 848@option{-nostdinc} is in effect. 849 850GCC looks for headers requested with @code{@w{#include "@var{file}"}} 851first in the directory containing the current file, then in the same 852places it would have looked for a header requested with angle brackets. 853For example, if @file{/usr/include/sys/stat.h} contains 854@code{@w{#include "types.h"}}, GCC looks for @file{types.h} first in 855@file{/usr/include/sys}, then in its usual search path. 856 857@samp{#line} (@pxref{Line Control}) does not change GCC's idea of the 858directory containing the current file. 859 860You may put @option{-I-} at any point in your list of @option{-I} options. 861This has two effects. First, directories appearing before the 862@option{-I-} in the list are searched only for headers requested with 863quote marks. Directories after @option{-I-} are searched for all 864headers. Second, the directory containing the current file is not 865searched for anything, unless it happens to be one of the directories 866named by an @option{-I} switch. 867 868@option{-I. -I-} is not the same as no @option{-I} options at all, and does 869not cause the same behavior for @samp{<>} includes that @samp{""} 870includes get with no special options. @option{-I.} searches the 871compiler's current working directory for header files. That may or may 872not be the same as the directory containing the current file. 873 874If you need to look for headers in a directory named @file{-}, write 875@option{-I./-}. 876 877There are several more ways to adjust the header search path. They are 878generally less useful. @xref{Invocation}. 879 880@node Once-Only Headers 881@section Once-Only Headers 882@cindex repeated inclusion 883@cindex including just once 884@cindex wrapper @code{#ifndef} 885 886If a header file happens to be included twice, the compiler will process 887its contents twice. This is very likely to cause an error, e.g.@: when the 888compiler sees the same structure definition twice. Even if it does not, 889it will certainly waste time. 890 891The standard way to prevent this is to enclose the entire real contents 892of the file in a conditional, like this: 893 894@example 895@group 896/* File foo. */ 897#ifndef FILE_FOO_SEEN 898#define FILE_FOO_SEEN 899 900@var{the entire file} 901 902#endif /* !FILE_FOO_SEEN */ 903@end group 904@end example 905 906This construct is commonly known as a @dfn{wrapper #ifndef}. 907When the header is included again, the conditional will be false, 908because @code{FILE_FOO_SEEN} is defined. The preprocessor will skip 909over the entire contents of the file, and the compiler will not see it 910twice. 911 912GNU CPP optimizes even further. It remembers when a header file has a 913wrapper @samp{#ifndef}. If a subsequent @samp{#include} specifies that 914header, and the macro in the @samp{#ifndef} is still defined, it does 915not bother to rescan the file at all. 916 917You can put comments outside the wrapper. They will not interfere with 918this optimization. 919 920@cindex controlling macro 921@cindex guard macro 922The macro @code{FILE_FOO_SEEN} is called the @dfn{controlling macro} or 923@dfn{guard macro}. In a user header file, the macro name should not 924begin with @samp{_}. In a system header file, it should begin with 925@samp{__} to avoid conflicts with user programs. In any kind of header 926file, the macro name should contain the name of the file and some 927additional text, to avoid conflicts with other header files. 928 929@node Computed Includes 930@section Computed Includes 931@cindex computed includes 932@cindex macros in include 933 934Sometimes it is necessary to select one of several different header 935files to be included into your program. They might specify 936configuration parameters to be used on different sorts of operating 937systems, for instance. You could do this with a series of conditionals, 938 939@example 940#if SYSTEM_1 941# include "system_1.h" 942#elif SYSTEM_2 943# include "system_2.h" 944#elif SYSTEM_3 945@dots{} 946#endif 947@end example 948 949That rapidly becomes tedious. Instead, the preprocessor offers the 950ability to use a macro for the header name. This is called a 951@dfn{computed include}. Instead of writing a header name as the direct 952argument of @samp{#include}, you simply put a macro name there instead: 953 954@example 955#define SYSTEM_H "system_1.h" 956@dots{} 957#include SYSTEM_H 958@end example 959 960@noindent 961@code{SYSTEM_H} will be expanded, and the preprocessor will look for 962@file{system_1.h} as if the @samp{#include} had been written that way 963originally. @code{SYSTEM_H} could be defined by your Makefile with a 964@option{-D} option. 965 966You must be careful when you define the macro. @samp{#define} saves 967tokens, not text. The preprocessor has no way of knowing that the macro 968will be used as the argument of @samp{#include}, so it generates 969ordinary tokens, not a header name. This is unlikely to cause problems 970if you use double-quote includes, which are close enough to string 971constants. If you use angle brackets, however, you may have trouble. 972 973The syntax of a computed include is actually a bit more general than the 974above. If the first non-whitespace character after @samp{#include} is 975not @samp{"} or @samp{<}, then the entire line is macro-expanded 976like running text would be. 977 978If the line expands to a single string constant, the contents of that 979string constant are the file to be included. CPP does not re-examine the 980string for embedded quotes, but neither does it process backslash 981escapes in the string. Therefore 982 983@example 984#define HEADER "a\"b" 985#include HEADER 986@end example 987 988@noindent 989looks for a file named @file{a\"b}. CPP searches for the file according 990to the rules for double-quoted includes. 991 992If the line expands to a token stream beginning with a @samp{<} token 993and including a @samp{>} token, then the tokens between the @samp{<} and 994the first @samp{>} are combined to form the filename to be included. 995Any whitespace between tokens is reduced to a single space; then any 996space after the initial @samp{<} is retained, but a trailing space 997before the closing @samp{>} is ignored. CPP searches for the file 998according to the rules for angle-bracket includes. 999 1000In either case, if there are any tokens on the line after the file name, 1001an error occurs and the directive is not processed. It is also an error 1002if the result of expansion does not match either of the two expected 1003forms. 1004 1005These rules are implementation-defined behavior according to the C 1006standard. To minimize the risk of different compilers interpreting your 1007computed includes differently, we recommend you use only a single 1008object-like macro which expands to a string constant. This will also 1009minimize confusion for people reading your program. 1010 1011@node Wrapper Headers 1012@section Wrapper Headers 1013@cindex wrapper headers 1014@cindex overriding a header file 1015@findex #include_next 1016 1017Sometimes it is necessary to adjust the contents of a system-provided 1018header file without editing it directly. GCC's @command{fixincludes} 1019operation does this, for example. One way to do that would be to create 1020a new header file with the same name and insert it in the search path 1021before the original header. That works fine as long as you're willing 1022to replace the old header entirely. But what if you want to refer to 1023the old header from the new one? 1024 1025You cannot simply include the old header with @samp{#include}. That 1026will start from the beginning, and find your new header again. If your 1027header is not protected from multiple inclusion (@pxref{Once-Only 1028Headers}), it will recurse infinitely and cause a fatal error. 1029 1030You could include the old header with an absolute pathname: 1031@example 1032#include "/usr/include/old-header.h" 1033@end example 1034@noindent 1035This works, but is not clean; should the system headers ever move, you 1036would have to edit the new headers to match. 1037 1038There is no way to solve this problem within the C standard, but you can 1039use the GNU extension @samp{#include_next}. It means, ``Include the 1040@emph{next} file with this name.'' This directive works like 1041@samp{#include} except in searching for the specified file: it starts 1042searching the list of header file directories @emph{after} the directory 1043in which the current file was found. 1044 1045Suppose you specify @option{-I /usr/local/include}, and the list of 1046directories to search also includes @file{/usr/include}; and suppose 1047both directories contain @file{signal.h}. Ordinary @code{@w{#include 1048<signal.h>}} finds the file under @file{/usr/local/include}. If that 1049file contains @code{@w{#include_next <signal.h>}}, it starts searching 1050after that directory, and finds the file in @file{/usr/include}. 1051 1052@samp{#include_next} does not distinguish between @code{<@var{file}>} 1053and @code{"@var{file}"} inclusion, nor does it check that the file you 1054specify has the same name as the current file. It simply looks for the 1055file named, starting with the directory in the search path after the one 1056where the current file was found. 1057 1058The use of @samp{#include_next} can lead to great confusion. We 1059recommend it be used only when there is no other alternative. In 1060particular, it should not be used in the headers belonging to a specific 1061program; it should be used only to make global corrections along the 1062lines of @command{fixincludes}. 1063 1064@node System Headers 1065@section System Headers 1066@cindex system header files 1067 1068The header files declaring interfaces to the operating system and 1069runtime libraries often cannot be written in strictly conforming C@. 1070Therefore, GCC gives code found in @dfn{system headers} special 1071treatment. All warnings, other than those generated by @samp{#warning} 1072(@pxref{Diagnostics}), are suppressed while GCC is processing a system 1073header. Macros defined in a system header are immune to a few warnings 1074wherever they are expanded. This immunity is granted on an ad-hoc 1075basis, when we find that a warning generates lots of false positives 1076because of code in macros defined in system headers. 1077 1078Normally, only the headers found in specific directories are considered 1079system headers. These directories are determined when GCC is compiled. 1080There are, however, two ways to make normal headers into system headers. 1081 1082The @option{-isystem} command line option adds its argument to the list of 1083directories to search for headers, just like @option{-I}. Any headers 1084found in that directory will be considered system headers. 1085 1086All directories named by @option{-isystem} are searched @emph{after} all 1087directories named by @option{-I}, no matter what their order was on the 1088command line. If the same directory is named by both @option{-I} and 1089@option{-isystem}, the @option{-I} option is ignored. GCC provides an 1090informative message when this occurs if @option{-v} is used. 1091 1092@findex #pragma GCC system_header 1093There is also a directive, @code{@w{#pragma GCC system_header}}, which 1094tells GCC to consider the rest of the current include file a system 1095header, no matter where it was found. Code that comes before the 1096@samp{#pragma} in the file will not be affected. @code{@w{#pragma GCC 1097system_header}} has no effect in the primary source file. 1098 1099On very old systems, some of the pre-defined system header directories 1100get even more special treatment. GNU C++ considers code in headers 1101found in those directories to be surrounded by an @code{@w{extern "C"}} 1102block. There is no way to request this behavior with a @samp{#pragma}, 1103or from the command line. 1104 1105@node Macros 1106@chapter Macros 1107 1108A @dfn{macro} is a fragment of code which has been given a name. 1109Whenever the name is used, it is replaced by the contents of the macro. 1110There are two kinds of macros. They differ mostly in what they look 1111like when they are used. @dfn{Object-like} macros resemble data objects 1112when used, @dfn{function-like} macros resemble function calls. 1113 1114You may define any valid identifier as a macro, even if it is a C 1115keyword. The preprocessor does not know anything about keywords. This 1116can be useful if you wish to hide a keyword such as @code{const} from an 1117older compiler that does not understand it. However, the preprocessor 1118operator @code{defined} (@pxref{Defined}) can never be defined as a 1119macro, and C++'s named operators (@pxref{C++ Named Operators}) cannot be 1120macros when you are compiling C++. 1121 1122@menu 1123* Object-like Macros:: 1124* Function-like Macros:: 1125* Macro Arguments:: 1126* Stringification:: 1127* Concatenation:: 1128* Variadic Macros:: 1129* Predefined Macros:: 1130* Undefining and Redefining Macros:: 1131* Macro Pitfalls:: 1132@end menu 1133 1134@node Object-like Macros 1135@section Object-like Macros 1136@cindex object-like macro 1137@cindex symbolic constants 1138@cindex manifest constants 1139 1140An @dfn{object-like macro} is a simple identifier which will be replaced 1141by a code fragment. It is called object-like because it looks like a 1142data object in code that uses it. They are most commonly used to give 1143symbolic names to numeric constants. 1144 1145@findex #define 1146You create macros with the @samp{#define} directive. @samp{#define} is 1147followed by the name of the macro and then the token sequence it should 1148be an abbreviation for, which is variously referred to as the macro's 1149@dfn{body}, @dfn{expansion} or @dfn{replacement list}. For example, 1150 1151@example 1152#define BUFFER_SIZE 1024 1153@end example 1154 1155@noindent 1156defines a macro named @code{BUFFER_SIZE} as an abbreviation for the 1157token @code{1024}. If somewhere after this @samp{#define} directive 1158there comes a C statement of the form 1159 1160@example 1161foo = (char *) malloc (BUFFER_SIZE); 1162@end example 1163 1164@noindent 1165then the C preprocessor will recognize and @dfn{expand} the macro 1166@code{BUFFER_SIZE}. The C compiler will see the same tokens as it would 1167if you had written 1168 1169@example 1170foo = (char *) malloc (1024); 1171@end example 1172 1173By convention, macro names are written in upper case. Programs are 1174easier to read when it is possible to tell at a glance which names are 1175macros. 1176 1177The macro's body ends at the end of the @samp{#define} line. You may 1178continue the definition onto multiple lines, if necessary, using 1179backslash-newline. When the macro is expanded, however, it will all 1180come out on one line. For example, 1181 1182@example 1183#define NUMBERS 1, \ 1184 2, \ 1185 3 1186int x[] = @{ NUMBERS @}; 1187 @expansion{} int x[] = @{ 1, 2, 3 @}; 1188@end example 1189 1190@noindent 1191The most common visible consequence of this is surprising line numbers 1192in error messages. 1193 1194There is no restriction on what can go in a macro body provided it 1195decomposes into valid preprocessing tokens. Parentheses need not 1196balance, and the body need not resemble valid C code. (If it does not, 1197you may get error messages from the C compiler when you use the macro.) 1198 1199The C preprocessor scans your program sequentially. Macro definitions 1200take effect at the place you write them. Therefore, the following input 1201to the C preprocessor 1202 1203@example 1204foo = X; 1205#define X 4 1206bar = X; 1207@end example 1208 1209@noindent 1210produces 1211 1212@example 1213foo = X; 1214bar = 4; 1215@end example 1216 1217When the preprocessor expands a macro name, the macro's expansion 1218replaces the macro invocation, then the expansion is examined for more 1219macros to expand. For example, 1220 1221@example 1222@group 1223#define TABLESIZE BUFSIZE 1224#define BUFSIZE 1024 1225TABLESIZE 1226 @expansion{} BUFSIZE 1227 @expansion{} 1024 1228@end group 1229@end example 1230 1231@noindent 1232@code{TABLESIZE} is expanded first to produce @code{BUFSIZE}, then that 1233macro is expanded to produce the final result, @code{1024}. 1234 1235Notice that @code{BUFSIZE} was not defined when @code{TABLESIZE} was 1236defined. The @samp{#define} for @code{TABLESIZE} uses exactly the 1237expansion you specify---in this case, @code{BUFSIZE}---and does not 1238check to see whether it too contains macro names. Only when you 1239@emph{use} @code{TABLESIZE} is the result of its expansion scanned for 1240more macro names. 1241 1242This makes a difference if you change the definition of @code{BUFSIZE} 1243at some point in the source file. @code{TABLESIZE}, defined as shown, 1244will always expand using the definition of @code{BUFSIZE} that is 1245currently in effect: 1246 1247@example 1248#define BUFSIZE 1020 1249#define TABLESIZE BUFSIZE 1250#undef BUFSIZE 1251#define BUFSIZE 37 1252@end example 1253 1254@noindent 1255Now @code{TABLESIZE} expands (in two stages) to @code{37}. 1256 1257If the expansion of a macro contains its own name, either directly or 1258via intermediate macros, it is not expanded again when the expansion is 1259examined for more macros. This prevents infinite recursion. 1260@xref{Self-Referential Macros}, for the precise details. 1261 1262@node Function-like Macros 1263@section Function-like Macros 1264@cindex function-like macros 1265 1266You can also define macros whose use looks like a function call. These 1267are called @dfn{function-like macros}. To define a function-like macro, 1268you use the same @samp{#define} directive, but you put a pair of 1269parentheses immediately after the macro name. For example, 1270 1271@example 1272#define lang_init() c_init() 1273lang_init() 1274 @expansion{} c_init() 1275@end example 1276 1277A function-like macro is only expanded if its name appears with a pair 1278of parentheses after it. If you write just the name, it is left alone. 1279This can be useful when you have a function and a macro of the same 1280name, and you wish to use the function sometimes. 1281 1282@example 1283extern void foo(void); 1284#define foo() /* optimized inline version */ 1285@dots{} 1286 foo(); 1287 funcptr = foo; 1288@end example 1289 1290Here the call to @code{foo()} will use the macro, but the function 1291pointer will get the address of the real function. If the macro were to 1292be expanded, it would cause a syntax error. 1293 1294If you put spaces between the macro name and the parentheses in the 1295macro definition, that does not define a function-like macro, it defines 1296an object-like macro whose expansion happens to begin with a pair of 1297parentheses. 1298 1299@example 1300#define lang_init () c_init() 1301lang_init() 1302 @expansion{} () c_init()() 1303@end example 1304 1305The first two pairs of parentheses in this expansion come from the 1306macro. The third is the pair that was originally after the macro 1307invocation. Since @code{lang_init} is an object-like macro, it does not 1308consume those parentheses. 1309 1310@node Macro Arguments 1311@section Macro Arguments 1312@cindex arguments 1313@cindex macros with arguments 1314@cindex arguments in macro definitions 1315 1316Function-like macros can take @dfn{arguments}, just like true functions. 1317To define a macro that uses arguments, you insert @dfn{parameters} 1318between the pair of parentheses in the macro definition that make the 1319macro function-like. The parameters must be valid C identifiers, 1320separated by commas and optionally whitespace. 1321 1322To invoke a macro that takes arguments, you write the name of the macro 1323followed by a list of @dfn{actual arguments} in parentheses, separated 1324by commas. The invocation of the macro need not be restricted to a 1325single logical line---it can cross as many lines in the source file as 1326you wish. The number of arguments you give must match the number of 1327parameters in the macro definition. When the macro is expanded, each 1328use of a parameter in its body is replaced by the tokens of the 1329corresponding argument. (You need not use all of the parameters in the 1330macro body.) 1331 1332As an example, here is a macro that computes the minimum of two numeric 1333values, as it is defined in many C programs, and some uses. 1334 1335@example 1336#define min(X, Y) ((X) < (Y) ? (X) : (Y)) 1337 x = min(a, b); @expansion{} x = ((a) < (b) ? (a) : (b)); 1338 y = min(1, 2); @expansion{} y = ((1) < (2) ? (1) : (2)); 1339 z = min(a + 28, *p); @expansion{} z = ((a + 28) < (*p) ? (a + 28) : (*p)); 1340@end example 1341 1342@noindent 1343(In this small example you can already see several of the dangers of 1344macro arguments. @xref{Macro Pitfalls}, for detailed explanations.) 1345 1346Leading and trailing whitespace in each argument is dropped, and all 1347whitespace between the tokens of an argument is reduced to a single 1348space. Parentheses within each argument must balance; a comma within 1349such parentheses does not end the argument. However, there is no 1350requirement for square brackets or braces to balance, and they do not 1351prevent a comma from separating arguments. Thus, 1352 1353@example 1354macro (array[x = y, x + 1]) 1355@end example 1356 1357@noindent 1358passes two arguments to @code{macro}: @code{array[x = y} and @code{x + 13591]}. If you want to supply @code{array[x = y, x + 1]} as an argument, 1360you can write it as @code{array[(x = y, x + 1)]}, which is equivalent C 1361code. 1362 1363All arguments to a macro are completely macro-expanded before they are 1364substituted into the macro body. After substitution, the complete text 1365is scanned again for macros to expand, including the arguments. This rule 1366may seem strange, but it is carefully designed so you need not worry 1367about whether any function call is actually a macro invocation. You can 1368run into trouble if you try to be too clever, though. @xref{Argument 1369Prescan}, for detailed discussion. 1370 1371For example, @code{min (min (a, b), c)} is first expanded to 1372 1373@example 1374 min (((a) < (b) ? (a) : (b)), (c)) 1375@end example 1376 1377@noindent 1378and then to 1379 1380@example 1381@group 1382((((a) < (b) ? (a) : (b))) < (c) 1383 ? (((a) < (b) ? (a) : (b))) 1384 : (c)) 1385@end group 1386@end example 1387 1388@noindent 1389(Line breaks shown here for clarity would not actually be generated.) 1390 1391@cindex empty macro arguments 1392You can leave macro arguments empty; this is not an error to the 1393preprocessor (but many macros will then expand to invalid code). 1394You cannot leave out arguments entirely; if a macro takes two arguments, 1395there must be exactly one comma at the top level of its argument list. 1396Here are some silly examples using @code{min}: 1397 1398@example 1399min(, b) @expansion{} (( ) < (b) ? ( ) : (b)) 1400min(a, ) @expansion{} ((a ) < ( ) ? (a ) : ( )) 1401min(,) @expansion{} (( ) < ( ) ? ( ) : ( )) 1402min((,),) @expansion{} (((,)) < ( ) ? ((,)) : ( )) 1403 1404min() @error{} macro "min" requires 2 arguments, but only 1 given 1405min(,,) @error{} macro "min" passed 3 arguments, but takes just 2 1406@end example 1407 1408Whitespace is not a preprocessing token, so if a macro @code{foo} takes 1409one argument, @code{@w{foo ()}} and @code{@w{foo ( )}} both supply it an 1410empty argument. Previous GNU preprocessor implementations and 1411documentation were incorrect on this point, insisting that a 1412function-like macro that takes a single argument be passed a space if an 1413empty argument was required. 1414 1415Macro parameters appearing inside string literals are not replaced by 1416their corresponding actual arguments. 1417 1418@example 1419#define foo(x) x, "x" 1420foo(bar) @expansion{} bar, "x" 1421@end example 1422 1423@node Stringification 1424@section Stringification 1425@cindex stringification 1426@cindex @samp{#} operator 1427 1428Sometimes you may want to convert a macro argument into a string 1429constant. Parameters are not replaced inside string constants, but you 1430can use the @samp{#} preprocessing operator instead. When a macro 1431parameter is used with a leading @samp{#}, the preprocessor replaces it 1432with the literal text of the actual argument, converted to a string 1433constant. Unlike normal parameter replacement, the argument is not 1434macro-expanded first. This is called @dfn{stringification}. 1435 1436There is no way to combine an argument with surrounding text and 1437stringify it all together. Instead, you can write a series of adjacent 1438string constants and stringified arguments. The preprocessor will 1439replace the stringified arguments with string constants. The C 1440compiler will then combine all the adjacent string constants into one 1441long string. 1442 1443Here is an example of a macro definition that uses stringification: 1444 1445@example 1446@group 1447#define WARN_IF(EXP) \ 1448do @{ if (EXP) \ 1449 fprintf (stderr, "Warning: " #EXP "\n"); @} \ 1450while (0) 1451WARN_IF (x == 0); 1452 @expansion{} do @{ if (x == 0) 1453 fprintf (stderr, "Warning: " "x == 0" "\n"); @} while (0); 1454@end group 1455@end example 1456 1457@noindent 1458The argument for @code{EXP} is substituted once, as-is, into the 1459@code{if} statement, and once, stringified, into the argument to 1460@code{fprintf}. If @code{x} were a macro, it would be expanded in the 1461@code{if} statement, but not in the string. 1462 1463The @code{do} and @code{while (0)} are a kludge to make it possible to 1464write @code{WARN_IF (@var{arg});}, which the resemblance of 1465@code{WARN_IF} to a function would make C programmers want to do; see 1466@ref{Swallowing the Semicolon}. 1467 1468Stringification in C involves more than putting double-quote characters 1469around the fragment. The preprocessor backslash-escapes the quotes 1470surrounding embedded string constants, and all backslashes within string and 1471character constants, in order to get a valid C string constant with the 1472proper contents. Thus, stringifying @code{@w{p = "foo\n";}} results in 1473@t{@w{"p = \"foo\\n\";"}}. However, backslashes that are not inside string 1474or character constants are not duplicated: @samp{\n} by itself 1475stringifies to @t{"\n"}. 1476 1477All leading and trailing whitespace in text being stringified is 1478ignored. Any sequence of whitespace in the middle of the text is 1479converted to a single space in the stringified result. Comments are 1480replaced by whitespace long before stringification happens, so they 1481never appear in stringified text. 1482 1483There is no way to convert a macro argument into a character constant. 1484 1485If you want to stringify the result of expansion of a macro argument, 1486you have to use two levels of macros. 1487 1488@example 1489#define xstr(s) str(s) 1490#define str(s) #s 1491#define foo 4 1492str (foo) 1493 @expansion{} "foo" 1494xstr (foo) 1495 @expansion{} xstr (4) 1496 @expansion{} str (4) 1497 @expansion{} "4" 1498@end example 1499 1500@code{s} is stringified when it is used in @code{str}, so it is not 1501macro-expanded first. But @code{s} is an ordinary argument to 1502@code{xstr}, so it is completely macro-expanded before @code{xstr} 1503itself is expanded (@pxref{Argument Prescan}). Therefore, by the time 1504@code{str} gets to its argument, it has already been macro-expanded. 1505 1506@node Concatenation 1507@section Concatenation 1508@cindex concatenation 1509@cindex token pasting 1510@cindex token concatenation 1511@cindex @samp{##} operator 1512 1513It is often useful to merge two tokens into one while expanding macros. 1514This is called @dfn{token pasting} or @dfn{token concatenation}. The 1515@samp{##} preprocessing operator performs token pasting. When a macro 1516is expanded, the two tokens on either side of each @samp{##} operator 1517are combined into a single token, which then replaces the @samp{##} and 1518the two original tokens in the macro expansion. Usually both will be 1519identifiers, or one will be an identifier and the other a preprocessing 1520number. When pasted, they make a longer identifier. This isn't the 1521only valid case. It is also possible to concatenate two numbers (or a 1522number and a name, such as @code{1.5} and @code{e3}) into a number. 1523Also, multi-character operators such as @code{+=} can be formed by 1524token pasting. 1525 1526However, two tokens that don't together form a valid token cannot be 1527pasted together. For example, you cannot concatenate @code{x} with 1528@code{+} in either order. If you try, the preprocessor issues a warning 1529and emits the two tokens. Whether it puts white space between the 1530tokens is undefined. It is common to find unnecessary uses of @samp{##} 1531in complex macros. If you get this warning, it is likely that you can 1532simply remove the @samp{##}. 1533 1534Both the tokens combined by @samp{##} could come from the macro body, 1535but you could just as well write them as one token in the first place. 1536Token pasting is most useful when one or both of the tokens comes from a 1537macro argument. If either of the tokens next to an @samp{##} is a 1538parameter name, it is replaced by its actual argument before @samp{##} 1539executes. As with stringification, the actual argument is not 1540macro-expanded first. If the argument is empty, that @samp{##} has no 1541effect. 1542 1543Keep in mind that the C preprocessor converts comments to whitespace 1544before macros are even considered. Therefore, you cannot create a 1545comment by concatenating @samp{/} and @samp{*}. You can put as much 1546whitespace between @samp{##} and its operands as you like, including 1547comments, and you can put comments in arguments that will be 1548concatenated. However, it is an error if @samp{##} appears at either 1549end of a macro body. 1550 1551Consider a C program that interprets named commands. There probably 1552needs to be a table of commands, perhaps an array of structures declared 1553as follows: 1554 1555@example 1556@group 1557struct command 1558@{ 1559 char *name; 1560 void (*function) (void); 1561@}; 1562@end group 1563 1564@group 1565struct command commands[] = 1566@{ 1567 @{ "quit", quit_command @}, 1568 @{ "help", help_command @}, 1569 @dots{} 1570@}; 1571@end group 1572@end example 1573 1574It would be cleaner not to have to give each command name twice, once in 1575the string constant and once in the function name. A macro which takes the 1576name of a command as an argument can make this unnecessary. The string 1577constant can be created with stringification, and the function name by 1578concatenating the argument with @samp{_command}. Here is how it is done: 1579 1580@example 1581#define COMMAND(NAME) @{ #NAME, NAME ## _command @} 1582 1583struct command commands[] = 1584@{ 1585 COMMAND (quit), 1586 COMMAND (help), 1587 @dots{} 1588@}; 1589@end example 1590 1591@node Variadic Macros 1592@section Variadic Macros 1593@cindex variable number of arguments 1594@cindex macros with variable arguments 1595@cindex variadic macros 1596 1597A macro can be declared to accept a variable number of arguments much as 1598a function can. The syntax for defining the macro is similar to that of 1599a function. Here is an example: 1600 1601@example 1602#define eprintf(@dots{}) fprintf (stderr, __VA_ARGS__) 1603@end example 1604 1605This kind of macro is called @dfn{variadic}. When the macro is invoked, 1606all the tokens in its argument list after the last named argument (this 1607macro has none), including any commas, become the @dfn{variable 1608argument}. This sequence of tokens replaces the identifier 1609@code{@w{__VA_ARGS__}} in the macro body wherever it appears. Thus, we 1610have this expansion: 1611 1612@example 1613eprintf ("%s:%d: ", input_file, lineno) 1614 @expansion{} fprintf (stderr, "%s:%d: ", input_file, lineno) 1615@end example 1616 1617The variable argument is completely macro-expanded before it is inserted 1618into the macro expansion, just like an ordinary argument. You may use 1619the @samp{#} and @samp{##} operators to stringify the variable argument 1620or to paste its leading or trailing token with another token. (But see 1621below for an important special case for @samp{##}.) 1622 1623If your macro is complicated, you may want a more descriptive name for 1624the variable argument than @code{@w{__VA_ARGS__}}. GNU CPP permits 1625this, as an extension. You may write an argument name immediately 1626before the @samp{@dots{}}; that name is used for the variable argument. 1627The @code{eprintf} macro above could be written 1628 1629@example 1630#define eprintf(args@dots{}) fprintf (stderr, args) 1631@end example 1632 1633@noindent 1634using this extension. You cannot use @code{__VA_ARGS__} and this 1635extension in the same macro. 1636 1637You can have named arguments as well as variable arguments in a variadic 1638macro. We could define @code{eprintf} like this, instead: 1639 1640@example 1641#define eprintf(format, @dots{}) fprintf (stderr, format, __VA_ARGS__) 1642@end example 1643 1644@noindent 1645This formulation looks more descriptive, but unfortunately it is less 1646flexible: you must now supply at least one argument after the format 1647string. In standard C, you cannot omit the comma separating the named 1648argument from the variable arguments. Furthermore, if you leave the 1649variable argument empty, you will get a syntax error, because 1650there will be an extra comma after the format string. 1651 1652@example 1653eprintf("success!\n", ); 1654 @expansion{} fprintf(stderr, "success!\n", ); 1655@end example 1656 1657GNU CPP has a pair of extensions which deal with this problem. First, 1658you are allowed to leave the variable argument out entirely: 1659 1660@example 1661eprintf ("success!\n") 1662 @expansion{} fprintf(stderr, "success!\n", ); 1663@end example 1664 1665@noindent 1666Second, the @samp{##} token paste operator has a special meaning when 1667placed between a comma and a variable argument. If you write 1668 1669@example 1670#define eprintf(format, @dots{}) fprintf (stderr, format, ##__VA_ARGS__) 1671@end example 1672 1673@noindent 1674and the variable argument is left out when the @code{eprintf} macro is 1675used, then the comma before the @samp{##} will be deleted. This does 1676@emph{not} happen if you pass an empty argument, nor does it happen if 1677the token preceding @samp{##} is anything other than a comma. 1678 1679@example 1680eprintf ("success!\n") 1681 @expansion{} fprintf(stderr, "success!\n"); 1682@end example 1683 1684@noindent 1685The above explanation is ambiguous about the case where the only macro 1686parameter is a variable arguments parameter, as it is meaningless to 1687try to distinguish whether no argument at all is an empty argument or 1688a missing argument. In this case the C99 standard is clear that the 1689comma must remain, however the existing GCC extension used to swallow 1690the comma. So CPP retains the comma when conforming to a specific C 1691standard, and drops it otherwise. 1692 1693C99 mandates that the only place the identifier @code{@w{__VA_ARGS__}} 1694can appear is in the replacement list of a variadic macro. It may not 1695be used as a macro name, macro argument name, or within a different type 1696of macro. It may also be forbidden in open text; the standard is 1697ambiguous. We recommend you avoid using it except for its defined 1698purpose. 1699 1700Variadic macros are a new feature in C99. GNU CPP has supported them 1701for a long time, but only with a named variable argument 1702(@samp{args@dots{}}, not @samp{@dots{}} and @code{@w{__VA_ARGS__}}). If you are 1703concerned with portability to previous versions of GCC, you should use 1704only named variable arguments. On the other hand, if you are concerned 1705with portability to other conforming implementations of C99, you should 1706use only @code{@w{__VA_ARGS__}}. 1707 1708Previous versions of GNU CPP implemented the comma-deletion extension 1709much more generally. We have restricted it in this release to minimize 1710the differences from C99. To get the same effect with both this and 1711previous versions of GCC, the token preceding the special @samp{##} must 1712be a comma, and there must be white space between that comma and 1713whatever comes immediately before it: 1714 1715@example 1716#define eprintf(format, args@dots{}) fprintf (stderr, format , ##args) 1717@end example 1718 1719@noindent 1720@xref{Differences from previous versions}, for the gory details. 1721 1722@node Predefined Macros 1723@section Predefined Macros 1724 1725@cindex predefined macros 1726Several object-like macros are predefined; you use them without 1727supplying their definitions. They fall into three classes: standard, 1728common, and system-specific. 1729 1730In C++, there is a fourth category, the named operators. They act like 1731predefined macros, but you cannot undefine them. 1732 1733@menu 1734* Standard Predefined Macros:: 1735* Common Predefined Macros:: 1736* System-specific Predefined Macros:: 1737* C++ Named Operators:: 1738@end menu 1739 1740@node Standard Predefined Macros 1741@subsection Standard Predefined Macros 1742@cindex standard predefined macros. 1743 1744The standard predefined macros are specified by the C and/or C++ 1745language standards, so they are available with all compilers that 1746implement those standards. Older compilers may not provide all of 1747them. Their names all start with double underscores. 1748 1749@table @code 1750@item __FILE__ 1751This macro expands to the name of the current input file, in the form of 1752a C string constant. This is the path by which the preprocessor opened 1753the file, not the short name specified in @samp{#include} or as the 1754input file name argument. For example, 1755@code{"/usr/local/include/myheader.h"} is a possible expansion of this 1756macro. 1757 1758@item __LINE__ 1759This macro expands to the current input line number, in the form of a 1760decimal integer constant. While we call it a predefined macro, it's 1761a pretty strange macro, since its ``definition'' changes with each 1762new line of source code. 1763@end table 1764 1765@code{__FILE__} and @code{__LINE__} are useful in generating an error 1766message to report an inconsistency detected by the program; the message 1767can state the source line at which the inconsistency was detected. For 1768example, 1769 1770@example 1771fprintf (stderr, "Internal error: " 1772 "negative string length " 1773 "%d at %s, line %d.", 1774 length, __FILE__, __LINE__); 1775@end example 1776 1777An @samp{#include} directive changes the expansions of @code{__FILE__} 1778and @code{__LINE__} to correspond to the included file. At the end of 1779that file, when processing resumes on the input file that contained 1780the @samp{#include} directive, the expansions of @code{__FILE__} and 1781@code{__LINE__} revert to the values they had before the 1782@samp{#include} (but @code{__LINE__} is then incremented by one as 1783processing moves to the line after the @samp{#include}). 1784 1785A @samp{#line} directive changes @code{__LINE__}, and may change 1786@code{__FILE__} as well. @xref{Line Control}. 1787 1788C99 introduces @code{__func__}, and GCC has provided @code{__FUNCTION__} 1789for a long time. Both of these are strings containing the name of the 1790current function (there are slight semantic differences; see the GCC 1791manual). Neither of them is a macro; the preprocessor does not know the 1792name of the current function. They tend to be useful in conjunction 1793with @code{__FILE__} and @code{__LINE__}, though. 1794 1795@table @code 1796 1797@item __DATE__ 1798This macro expands to a string constant that describes the date on which 1799the preprocessor is being run. The string constant contains eleven 1800characters and looks like @code{@w{"Feb 12 1996"}}. If the day of the 1801month is less than 10, it is padded with a space on the left. 1802 1803@item __TIME__ 1804This macro expands to a string constant that describes the time at 1805which the preprocessor is being run. The string constant contains 1806eight characters and looks like @code{"23:59:01"}. 1807 1808@item __STDC__ 1809In normal operation, this macro expands to the constant 1, to signify 1810that this compiler conforms to ISO Standard C@. If GNU CPP is used with 1811a compiler other than GCC, this is not necessarily true; however, the 1812preprocessor always conforms to the standard, unless the 1813@option{-traditional} option is used. 1814 1815This macro is not defined if the @option{-traditional} option is used. 1816 1817On some hosts, the system compiler uses a different convention, where 1818@code{__STDC__} is normally 0, but is 1 if the user specifies strict 1819conformance to the C Standard. GNU CPP follows the host convention when 1820processing system header files, but when processing user files 1821@code{__STDC__} is always 1. This has been reported to cause problems; 1822for instance, some versions of Solaris provide X Windows headers that 1823expect @code{__STDC__} to be either undefined or 1. @xref{Invocation}. 1824 1825@item __STDC_VERSION__ 1826This macro expands to the C Standard's version number, a long integer 1827constant of the form @code{@var{yyyy}@var{mm}L} where @var{yyyy} and 1828@var{mm} are the year and month of the Standard version. This signifies 1829which version of the C Standard the compiler conforms to. Like 1830@code{__STDC__}, this is not necessarily accurate for the entire 1831implementation, unless GNU CPP is being used with GCC@. 1832 1833The value @code{199409L} signifies the 1989 C standard as amended in 18341994, which is the current default; the value @code{199901L} signifies 1835the 1999 revision of the C standard. Support for the 1999 revision is 1836not yet complete. 1837 1838This macro is not defined if the @option{-traditional} option is used, nor 1839when compiling C++ or Objective-C@. 1840 1841@item __STDC_HOSTED__ 1842This macro is defined, with value 1, if the compiler's target is a 1843@dfn{hosted environment}. A hosted environment has the complete 1844facilities of the standard C library available. 1845 1846@item __cplusplus 1847This macro is defined when the C++ compiler is in use. You can use 1848@code{__cplusplus} to test whether a header is compiled by a C compiler 1849or a C++ compiler. This macro is similar to @code{__STDC_VERSION__}, in 1850that it expands to a version number. A fully conforming implementation 1851of the 1998 C++ standard will define this macro to @code{199711L}. The 1852GNU C++ compiler is not yet fully conforming, so it uses @code{1} 1853instead. We hope to complete our implementation in the near future. 1854 1855@end table 1856 1857@node Common Predefined Macros 1858@subsection Common Predefined Macros 1859@cindex common predefined macros 1860 1861The common predefined macros are GNU C extensions. They are available 1862with the same meanings regardless of the machine or operating system on 1863which you are using GNU C@. Their names all start with double 1864underscores. 1865 1866@table @code 1867 1868@item __GNUC__ 1869@itemx __GNUC_MINOR__ 1870@itemx __GNUC_PATCHLEVEL__ 1871These macros are defined by all GNU compilers that use the C 1872preprocessor: C, C++, and Objective-C@. Their values are the major 1873version, minor version, and patch level of the compiler, as integer 1874constants. For example, GCC 3.2.1 will define @code{__GNUC__} to 3, 1875@code{__GNUC_MINOR__} to 2, and @code{__GNUC_PATCHLEVEL__} to 1. They 1876are defined only when the entire compiler is in use; if you invoke the 1877preprocessor directly, they are not defined. 1878 1879@code{__GNUC_PATCHLEVEL__} is new to GCC 3.0; it is also present in the 1880widely-used development snapshots leading up to 3.0 (which identify 1881themselves as GCC 2.96 or 2.97, depending on which snapshot you have). 1882 1883If all you need to know is whether or not your program is being compiled 1884by GCC, you can simply test @code{__GNUC__}. If you need to write code 1885which depends on a specific version, you must be more careful. Each 1886time the minor version is increased, the patch level is reset to zero; 1887each time the major version is increased (which happens rarely), the 1888minor version and patch level are reset. If you wish to use the 1889predefined macros directly in the conditional, you will need to write it 1890like this: 1891 1892@example 1893/* @r{Test for GCC > 3.2.0} */ 1894#if __GNUC__ > 3 || \ 1895 (__GNUC__ == 3 && (__GNUC_MINOR__ > 2 || \ 1896 (__GNUC_MINOR__ == 2 && \ 1897 __GNUC_PATCHLEVEL__ > 0)) 1898@end example 1899 1900@noindent 1901Another approach is to use the predefined macros to 1902calculate a single number, then compare that against a threshold: 1903 1904@example 1905#define GCC_VERSION (__GNUC__ * 10000 \ 1906 + __GNUC_MINOR__ * 100 \ 1907 + __GNUC_PATCHLEVEL__) 1908@dots{} 1909/* @r{Test for GCC > 3.2.0} */ 1910#if GCC_VERSION > 30200 1911@end example 1912 1913@noindent 1914Many people find this form easier to understand. 1915 1916@item __OBJC__ 1917This macro is defined, with value 1, when the Objective-C compiler is in 1918use. You can use @code{__OBJC__} to test whether a header is compiled 1919by a C compiler or a Objective-C compiler. 1920 1921@item __GNUG__ 1922The GNU C++ compiler defines this. Testing it is equivalent to 1923testing @code{@w{(__GNUC__ && __cplusplus)}}. 1924 1925@item __STRICT_ANSI__ 1926GCC defines this macro if and only if the @option{-ansi} switch, or a 1927@option{-std} switch specifying strict conformance to some version of ISO C, 1928was specified when GCC was invoked. It is defined to @samp{1}. 1929This macro exists primarily to direct GNU libc's header files to 1930restrict their definitions to the minimal set found in the 1989 C 1931standard. 1932 1933@item __BASE_FILE__ 1934This macro expands to the name of the main input file, in the form 1935of a C string constant. This is the source file that was specified 1936on the command line of the preprocessor or C compiler. 1937 1938@item __INCLUDE_LEVEL__ 1939This macro expands to a decimal integer constant that represents the 1940depth of nesting in include files. The value of this macro is 1941incremented on every @samp{#include} directive and decremented at the 1942end of every included file. It starts out at 0, it's value within the 1943base file specified on the command line. 1944 1945@item __VERSION__ 1946This macro expands to a string constant which describes the version of 1947the compiler in use. You should not rely on its contents having any 1948particular form, but it can be counted on to contain at least the 1949release number. 1950 1951@item __OPTIMIZE__ 1952@itemx __OPTIMIZE_SIZE__ 1953@itemx __NO_INLINE__ 1954These macros describe the compilation mode. @code{__OPTIMIZE__} is 1955defined in all optimizing compilations. @code{__OPTIMIZE_SIZE__} is 1956defined if the compiler is optimizing for size, not speed. 1957@code{__NO_INLINE__} is defined if no functions will be inlined into 1958their callers (when not optimizing, or when inlining has been 1959specifically disabled by @option{-fno-inline}). 1960 1961These macros cause certain GNU header files to provide optimized 1962definitions, using macros or inline functions, of system library 1963functions. You should not use these macros in any way unless you make 1964sure that programs will execute with the same effect whether or not they 1965are defined. If they are defined, their value is 1. 1966 1967@item __CHAR_UNSIGNED__ 1968GCC defines this macro if and only if the data type @code{char} is 1969unsigned on the target machine. It exists to cause the standard header 1970file @file{limits.h} to work correctly. You should not use this macro 1971yourself; instead, refer to the standard macros defined in @file{limits.h}. 1972 1973@item __REGISTER_PREFIX__ 1974This macro expands to a single token (not a string constant) which is 1975the prefix applied to CPU register names in assembly language for this 1976target. You can use it to write assembly that is usable in multiple 1977environments. For example, in the @code{m68k-aout} environment it 1978expands to nothing, but in the @code{m68k-coff} environment it expands 1979to a single @samp{%}. 1980 1981@item __USER_LABEL_PREFIX__ 1982This macro expands to a single token which is the prefix applied to 1983user labels (symbols visible to C code) in assembly. For example, in 1984the @code{m68k-aout} environment it expands to an @samp{_}, but in the 1985@code{m68k-coff} environment it expands to nothing. 1986 1987This macro will have the correct definition even if 1988@option{-f(no-)underscores} is in use, but it will not be correct if 1989target-specific options that adjust this prefix are used (e.g.@: the 1990OSF/rose @option{-mno-underscores} option). 1991 1992@item __SIZE_TYPE__ 1993@itemx __PTRDIFF_TYPE__ 1994@itemx __WCHAR_TYPE__ 1995@itemx __WINT_TYPE__ 1996These macros are defined to the correct underlying types for the 1997@code{size_t}, @code{ptrdiff_t}, @code{wchar_t}, and @code{wint_t} 1998typedefs, respectively. They exist to make the standard header files 1999@file{stddef.h} and @file{wchar.h} work correctly. You should not use 2000these macros directly; instead, include the appropriate headers and use 2001the typedefs. 2002 2003@item __USING_SJLJ_EXCEPTIONS__ 2004This macro is defined, with value 1, if the compiler uses the old 2005mechanism based on @code{setjmp} and @code{longjmp} for exception 2006handling. 2007@end table 2008 2009@node System-specific Predefined Macros 2010@subsection System-specific Predefined Macros 2011 2012@cindex system-specific predefined macros 2013@cindex predefined macros, system-specific 2014@cindex reserved namespace 2015 2016The C preprocessor normally predefines several macros that indicate what 2017type of system and machine is in use. They are obviously different on 2018each target supported by GCC@. This manual, being for all systems and 2019machines, cannot tell you what their names are, but you can use 2020@command{cpp -dM} to see them all. @xref{Invocation}. All system-specific 2021predefined macros expand to the constant 1, so you can test them with 2022either @samp{#ifdef} or @samp{#if}. 2023 2024The C standard requires that all system-specific macros be part of the 2025@dfn{reserved namespace}. All names which begin with two underscores, 2026or an underscore and a capital letter, are reserved for the compiler and 2027library to use as they wish. However, historically system-specific 2028macros have had names with no special prefix; for instance, it is common 2029to find @code{unix} defined on Unix systems. For all such macros, GCC 2030provides a parallel macro with two underscores added at the beginning 2031and the end. If @code{unix} is defined, @code{__unix__} will be defined 2032too. There will never be more than two underscores; the parallel of 2033@code{_mips} is @code{__mips__}. 2034 2035When the @option{-ansi} option, or any @option{-std} option that 2036requests strict conformance, is given to the compiler, all the 2037system-specific predefined macros outside the reserved namespace are 2038suppressed. The parallel macros, inside the reserved namespace, remain 2039defined. 2040 2041We are slowly phasing out all predefined macros which are outside the 2042reserved namespace. You should never use them in new programs, and we 2043encourage you to correct older code to use the parallel macros whenever 2044you find it. We don't recommend you use the system-specific macros that 2045are in the reserved namespace, either. It is better in the long run to 2046check specifically for features you need, using a tool such as 2047@command{autoconf}. 2048 2049@node C++ Named Operators 2050@subsection C++ Named Operators 2051@cindex named operators 2052@cindex C++ named operators 2053@cindex iso646.h 2054 2055In C++, there are eleven keywords which are simply alternate spellings 2056of operators normally written with punctuation. These keywords are 2057treated as such even in the preprocessor. They function as operators in 2058@samp{#if}, and they cannot be defined as macros or poisoned. In C, you 2059can request that those keywords take their C++ meaning by including 2060@file{iso646.h}. That header defines each one as a normal object-like 2061macro expanding to the appropriate punctuator. 2062 2063These are the named operators and their corresponding punctuators: 2064 2065@multitable {Named Operator} {Punctuator} 2066@item Named Operator @tab Punctuator 2067@item @code{and} @tab @code{&&} 2068@item @code{and_eq} @tab @code{&=} 2069@item @code{bitand} @tab @code{&} 2070@item @code{bitor} @tab @code{|} 2071@item @code{compl} @tab @code{~} 2072@item @code{not} @tab @code{!} 2073@item @code{not_eq} @tab @code{!=} 2074@item @code{or} @tab @code{||} 2075@item @code{or_eq} @tab @code{|=} 2076@item @code{xor} @tab @code{^} 2077@item @code{xor_eq} @tab @code{^=} 2078@end multitable 2079 2080@node Undefining and Redefining Macros 2081@section Undefining and Redefining Macros 2082@cindex undefining macros 2083@cindex redefining macros 2084@findex #undef 2085 2086If a macro ceases to be useful, it may be @dfn{undefined} with the 2087@samp{#undef} directive. @samp{#undef} takes a single argument, the 2088name of the macro to undefine. You use the bare macro name, even if the 2089macro is function-like. It is an error if anything appears on the line 2090after the macro name. @samp{#undef} has no effect if the name is not a 2091macro. 2092 2093@example 2094#define FOO 4 2095x = FOO; @expansion{} x = 4; 2096#undef FOO 2097x = FOO; @expansion{} x = FOO; 2098@end example 2099 2100Once a macro has been undefined, that identifier may be @dfn{redefined} 2101as a macro by a subsequent @samp{#define} directive. The new definition 2102need not have any resemblance to the old definition. 2103 2104However, if an identifier which is currently a macro is redefined, then 2105the new definition must be @dfn{effectively the same} as the old one. 2106Two macro definitions are effectively the same if: 2107@itemize @bullet 2108@item Both are the same type of macro (object- or function-like). 2109@item All the tokens of the replacement list are the same. 2110@item If there are any parameters, they are the same. 2111@item Whitespace appears in the same places in both. It need not be 2112exactly the same amount of whitespace, though. Remember that comments 2113count as whitespace. 2114@end itemize 2115 2116@noindent 2117These definitions are effectively the same: 2118@example 2119#define FOUR (2 + 2) 2120#define FOUR (2 + 2) 2121#define FOUR (2 /* two */ + 2) 2122@end example 2123@noindent 2124but these are not: 2125@example 2126#define FOUR (2 + 2) 2127#define FOUR ( 2+2 ) 2128#define FOUR (2 * 2) 2129#define FOUR(score,and,seven,years,ago) (2 + 2) 2130@end example 2131 2132If a macro is redefined with a definition that is not effectively the 2133same as the old one, the preprocessor issues a warning and changes the 2134macro to use the new definition. If the new definition is effectively 2135the same, the redefinition is silently ignored. This allows, for 2136instance, two different headers to define a common macro. The 2137preprocessor will only complain if the definitions do not match. 2138 2139@node Macro Pitfalls 2140@section Macro Pitfalls 2141@cindex problems with macros 2142@cindex pitfalls of macros 2143 2144In this section we describe some special rules that apply to macros and 2145macro expansion, and point out certain cases in which the rules have 2146counter-intuitive consequences that you must watch out for. 2147 2148@menu 2149* Misnesting:: 2150* Operator Precedence Problems:: 2151* Swallowing the Semicolon:: 2152* Duplication of Side Effects:: 2153* Self-Referential Macros:: 2154* Argument Prescan:: 2155* Newlines in Arguments:: 2156@end menu 2157 2158@node Misnesting 2159@subsection Misnesting 2160 2161When a macro is called with arguments, the arguments are substituted 2162into the macro body and the result is checked, together with the rest of 2163the input file, for more macro calls. It is possible to piece together 2164a macro call coming partially from the macro body and partially from the 2165arguments. For example, 2166 2167@example 2168#define twice(x) (2*(x)) 2169#define call_with_1(x) x(1) 2170call_with_1 (twice) 2171 @expansion{} twice(1) 2172 @expansion{} (2*(1)) 2173@end example 2174 2175Macro definitions do not have to have balanced parentheses. By writing 2176an unbalanced open parenthesis in a macro body, it is possible to create 2177a macro call that begins inside the macro body but ends outside of it. 2178For example, 2179 2180@example 2181#define strange(file) fprintf (file, "%s %d", 2182@dots{} 2183strange(stderr) p, 35) 2184 @expansion{} fprintf (stderr, "%s %d", p, 35) 2185@end example 2186 2187The ability to piece together a macro call can be useful, but the use of 2188unbalanced open parentheses in a macro body is just confusing, and 2189should be avoided. 2190 2191@node Operator Precedence Problems 2192@subsection Operator Precedence Problems 2193@cindex parentheses in macro bodies 2194 2195You may have noticed that in most of the macro definition examples shown 2196above, each occurrence of a macro argument name had parentheses around 2197it. In addition, another pair of parentheses usually surround the 2198entire macro definition. Here is why it is best to write macros that 2199way. 2200 2201Suppose you define a macro as follows, 2202 2203@example 2204#define ceil_div(x, y) (x + y - 1) / y 2205@end example 2206 2207@noindent 2208whose purpose is to divide, rounding up. (One use for this operation is 2209to compute how many @code{int} objects are needed to hold a certain 2210number of @code{char} objects.) Then suppose it is used as follows: 2211 2212@example 2213a = ceil_div (b & c, sizeof (int)); 2214 @expansion{} a = (b & c + sizeof (int) - 1) / sizeof (int); 2215@end example 2216 2217@noindent 2218This does not do what is intended. The operator-precedence rules of 2219C make it equivalent to this: 2220 2221@example 2222a = (b & (c + sizeof (int) - 1)) / sizeof (int); 2223@end example 2224 2225@noindent 2226What we want is this: 2227 2228@example 2229a = ((b & c) + sizeof (int) - 1)) / sizeof (int); 2230@end example 2231 2232@noindent 2233Defining the macro as 2234 2235@example 2236#define ceil_div(x, y) ((x) + (y) - 1) / (y) 2237@end example 2238 2239@noindent 2240provides the desired result. 2241 2242Unintended grouping can result in another way. Consider @code{sizeof 2243ceil_div(1, 2)}. That has the appearance of a C expression that would 2244compute the size of the type of @code{ceil_div (1, 2)}, but in fact it 2245means something very different. Here is what it expands to: 2246 2247@example 2248sizeof ((1) + (2) - 1) / (2) 2249@end example 2250 2251@noindent 2252This would take the size of an integer and divide it by two. The 2253precedence rules have put the division outside the @code{sizeof} when it 2254was intended to be inside. 2255 2256Parentheses around the entire macro definition prevent such problems. 2257Here, then, is the recommended way to define @code{ceil_div}: 2258 2259@example 2260#define ceil_div(x, y) (((x) + (y) - 1) / (y)) 2261@end example 2262 2263@node Swallowing the Semicolon 2264@subsection Swallowing the Semicolon 2265@cindex semicolons (after macro calls) 2266 2267Often it is desirable to define a macro that expands into a compound 2268statement. Consider, for example, the following macro, that advances a 2269pointer (the argument @code{p} says where to find it) across whitespace 2270characters: 2271 2272@example 2273#define SKIP_SPACES(p, limit) \ 2274@{ char *lim = (limit); \ 2275 while (p < lim) @{ \ 2276 if (*p++ != ' ') @{ \ 2277 p--; break; @}@}@} 2278@end example 2279 2280@noindent 2281Here backslash-newline is used to split the macro definition, which must 2282be a single logical line, so that it resembles the way such code would 2283be laid out if not part of a macro definition. 2284 2285A call to this macro might be @code{SKIP_SPACES (p, lim)}. Strictly 2286speaking, the call expands to a compound statement, which is a complete 2287statement with no need for a semicolon to end it. However, since it 2288looks like a function call, it minimizes confusion if you can use it 2289like a function call, writing a semicolon afterward, as in 2290@code{SKIP_SPACES (p, lim);} 2291 2292This can cause trouble before @code{else} statements, because the 2293semicolon is actually a null statement. Suppose you write 2294 2295@example 2296if (*p != 0) 2297 SKIP_SPACES (p, lim); 2298else @dots{} 2299@end example 2300 2301@noindent 2302The presence of two statements---the compound statement and a null 2303statement---in between the @code{if} condition and the @code{else} 2304makes invalid C code. 2305 2306The definition of the macro @code{SKIP_SPACES} can be altered to solve 2307this problem, using a @code{do @dots{} while} statement. Here is how: 2308 2309@example 2310#define SKIP_SPACES(p, limit) \ 2311do @{ char *lim = (limit); \ 2312 while (p < lim) @{ \ 2313 if (*p++ != ' ') @{ \ 2314 p--; break; @}@}@} \ 2315while (0) 2316@end example 2317 2318Now @code{SKIP_SPACES (p, lim);} expands into 2319 2320@example 2321do @{@dots{}@} while (0); 2322@end example 2323 2324@noindent 2325which is one statement. The loop executes exactly once; most compilers 2326generate no extra code for it. 2327 2328@node Duplication of Side Effects 2329@subsection Duplication of Side Effects 2330 2331@cindex side effects (in macro arguments) 2332@cindex unsafe macros 2333Many C programs define a macro @code{min}, for ``minimum'', like this: 2334 2335@example 2336#define min(X, Y) ((X) < (Y) ? (X) : (Y)) 2337@end example 2338 2339When you use this macro with an argument containing a side effect, 2340as shown here, 2341 2342@example 2343next = min (x + y, foo (z)); 2344@end example 2345 2346@noindent 2347it expands as follows: 2348 2349@example 2350next = ((x + y) < (foo (z)) ? (x + y) : (foo (z))); 2351@end example 2352 2353@noindent 2354where @code{x + y} has been substituted for @code{X} and @code{foo (z)} 2355for @code{Y}. 2356 2357The function @code{foo} is used only once in the statement as it appears 2358in the program, but the expression @code{foo (z)} has been substituted 2359twice into the macro expansion. As a result, @code{foo} might be called 2360two times when the statement is executed. If it has side effects or if 2361it takes a long time to compute, the results might not be what you 2362intended. We say that @code{min} is an @dfn{unsafe} macro. 2363 2364The best solution to this problem is to define @code{min} in a way that 2365computes the value of @code{foo (z)} only once. The C language offers 2366no standard way to do this, but it can be done with GNU extensions as 2367follows: 2368 2369@example 2370#define min(X, Y) \ 2371(@{ typeof (X) x_ = (X); \ 2372 typeof (Y) y_ = (Y); \ 2373 (x_ < y_) ? x_ : y_; @}) 2374@end example 2375 2376The @samp{(@{ @dots{} @})} notation produces a compound statement that 2377acts as an expression. Its value is the value of its last statement. 2378This permits us to define local variables and assign each argument to 2379one. The local variables have underscores after their names to reduce 2380the risk of conflict with an identifier of wider scope (it is impossible 2381to avoid this entirely). Now each argument is evaluated exactly once. 2382 2383If you do not wish to use GNU C extensions, the only solution is to be 2384careful when @emph{using} the macro @code{min}. For example, you can 2385calculate the value of @code{foo (z)}, save it in a variable, and use 2386that variable in @code{min}: 2387 2388@example 2389@group 2390#define min(X, Y) ((X) < (Y) ? (X) : (Y)) 2391@dots{} 2392@{ 2393 int tem = foo (z); 2394 next = min (x + y, tem); 2395@} 2396@end group 2397@end example 2398 2399@noindent 2400(where we assume that @code{foo} returns type @code{int}). 2401 2402@node Self-Referential Macros 2403@subsection Self-Referential Macros 2404@cindex self-reference 2405 2406A @dfn{self-referential} macro is one whose name appears in its 2407definition. Recall that all macro definitions are rescanned for more 2408macros to replace. If the self-reference were considered a use of the 2409macro, it would produce an infinitely large expansion. To prevent this, 2410the self-reference is not considered a macro call. It is passed into 2411the preprocessor output unchanged. Let's consider an example: 2412 2413@example 2414#define foo (4 + foo) 2415@end example 2416 2417@noindent 2418where @code{foo} is also a variable in your program. 2419 2420Following the ordinary rules, each reference to @code{foo} will expand 2421into @code{(4 + foo)}; then this will be rescanned and will expand into 2422@code{(4 + (4 + foo))}; and so on until the computer runs out of memory. 2423 2424The self-reference rule cuts this process short after one step, at 2425@code{(4 + foo)}. Therefore, this macro definition has the possibly 2426useful effect of causing the program to add 4 to the value of @code{foo} 2427wherever @code{foo} is referred to. 2428 2429In most cases, it is a bad idea to take advantage of this feature. A 2430person reading the program who sees that @code{foo} is a variable will 2431not expect that it is a macro as well. The reader will come across the 2432identifier @code{foo} in the program and think its value should be that 2433of the variable @code{foo}, whereas in fact the value is four greater. 2434 2435One common, useful use of self-reference is to create a macro which 2436expands to itself. If you write 2437 2438@example 2439#define EPERM EPERM 2440@end example 2441 2442@noindent 2443then the macro @code{EPERM} expands to @code{EPERM}. Effectively, it is 2444left alone by the preprocessor whenever it's used in running text. You 2445can tell that it's a macro with @samp{#ifdef}. You might do this if you 2446want to define numeric constants with an @code{enum}, but have 2447@samp{#ifdef} be true for each constant. 2448 2449If a macro @code{x} expands to use a macro @code{y}, and the expansion of 2450@code{y} refers to the macro @code{x}, that is an @dfn{indirect 2451self-reference} of @code{x}. @code{x} is not expanded in this case 2452either. Thus, if we have 2453 2454@example 2455#define x (4 + y) 2456#define y (2 * x) 2457@end example 2458 2459@noindent 2460then @code{x} and @code{y} expand as follows: 2461 2462@example 2463@group 2464x @expansion{} (4 + y) 2465 @expansion{} (4 + (2 * x)) 2466 2467y @expansion{} (2 * x) 2468 @expansion{} (2 * (4 + y)) 2469@end group 2470@end example 2471 2472@noindent 2473Each macro is expanded when it appears in the definition of the other 2474macro, but not when it indirectly appears in its own definition. 2475 2476@node Argument Prescan 2477@subsection Argument Prescan 2478@cindex expansion of arguments 2479@cindex macro argument expansion 2480@cindex prescan of macro arguments 2481 2482Macro arguments are completely macro-expanded before they are 2483substituted into a macro body, unless they are stringified or pasted 2484with other tokens. After substitution, the entire macro body, including 2485the substituted arguments, is scanned again for macros to be expanded. 2486The result is that the arguments are scanned @emph{twice} to expand 2487macro calls in them. 2488 2489Most of the time, this has no effect. If the argument contained any 2490macro calls, they are expanded during the first scan. The result 2491therefore contains no macro calls, so the second scan does not change 2492it. If the argument were substituted as given, with no prescan, the 2493single remaining scan would find the same macro calls and produce the 2494same results. 2495 2496You might expect the double scan to change the results when a 2497self-referential macro is used in an argument of another macro 2498(@pxref{Self-Referential Macros}): the self-referential macro would be 2499expanded once in the first scan, and a second time in the second scan. 2500However, this is not what happens. The self-references that do not 2501expand in the first scan are marked so that they will not expand in the 2502second scan either. 2503 2504You might wonder, ``Why mention the prescan, if it makes no difference? 2505And why not skip it and make the preprocessor faster?'' The answer is 2506that the prescan does make a difference in three special cases: 2507 2508@itemize @bullet 2509@item 2510Nested calls to a macro. 2511 2512We say that @dfn{nested} calls to a macro occur when a macro's argument 2513contains a call to that very macro. For example, if @code{f} is a macro 2514that expects one argument, @code{f (f (1))} is a nested pair of calls to 2515@code{f}. The desired expansion is made by expanding @code{f (1)} and 2516substituting that into the definition of @code{f}. The prescan causes 2517the expected result to happen. Without the prescan, @code{f (1)} itself 2518would be substituted as an argument, and the inner use of @code{f} would 2519appear during the main scan as an indirect self-reference and would not 2520be expanded. 2521 2522@item 2523Macros that call other macros that stringify or concatenate. 2524 2525If an argument is stringified or concatenated, the prescan does not 2526occur. If you @emph{want} to expand a macro, then stringify or 2527concatenate its expansion, you can do that by causing one macro to call 2528another macro that does the stringification or concatenation. For 2529instance, if you have 2530 2531@example 2532#define AFTERX(x) X_ ## x 2533#define XAFTERX(x) AFTERX(x) 2534#define TABLESIZE 1024 2535#define BUFSIZE TABLESIZE 2536@end example 2537 2538then @code{AFTERX(BUFSIZE)} expands to @code{X_BUFSIZE}, and 2539@code{XAFTERX(BUFSIZE)} expands to @code{X_1024}. (Not to 2540@code{X_TABLESIZE}. Prescan always does a complete expansion.) 2541 2542@item 2543Macros used in arguments, whose expansions contain unshielded commas. 2544 2545This can cause a macro expanded on the second scan to be called with the 2546wrong number of arguments. Here is an example: 2547 2548@example 2549#define foo a,b 2550#define bar(x) lose(x) 2551#define lose(x) (1 + (x)) 2552@end example 2553 2554We would like @code{bar(foo)} to turn into @code{(1 + (foo))}, which 2555would then turn into @code{(1 + (a,b))}. Instead, @code{bar(foo)} 2556expands into @code{lose(a,b)}, and you get an error because @code{lose} 2557requires a single argument. In this case, the problem is easily solved 2558by the same parentheses that ought to be used to prevent misnesting of 2559arithmetic operations: 2560 2561@example 2562#define foo (a,b) 2563@exdent or 2564#define bar(x) lose((x)) 2565@end example 2566 2567The extra pair of parentheses prevents the comma in @code{foo}'s 2568definition from being interpreted as an argument separator. 2569 2570@end itemize 2571 2572@node Newlines in Arguments 2573@subsection Newlines in Arguments 2574@cindex newlines in macro arguments 2575 2576The invocation of a function-like macro can extend over many logical 2577lines. However, in the present implementation, the entire expansion 2578comes out on one line. Thus line numbers emitted by the compiler or 2579debugger refer to the line the invocation started on, which might be 2580different to the line containing the argument causing the problem. 2581 2582Here is an example illustrating this: 2583 2584@example 2585#define ignore_second_arg(a,b,c) a; c 2586 2587ignore_second_arg (foo (), 2588 ignored (), 2589 syntax error); 2590@end example 2591 2592@noindent 2593The syntax error triggered by the tokens @code{syntax error} results in 2594an error message citing line three---the line of ignore_second_arg--- 2595even though the problematic code comes from line five. 2596 2597We consider this a bug, and intend to fix it in the near future. 2598 2599@node Conditionals 2600@chapter Conditionals 2601@cindex conditionals 2602 2603A @dfn{conditional} is a directive that instructs the preprocessor to 2604select whether or not to include a chunk of code in the final token 2605stream passed to the compiler. Preprocessor conditionals can test 2606arithmetic expressions, or whether a name is defined as a macro, or both 2607simultaneously using the special @code{defined} operator. 2608 2609A conditional in the C preprocessor resembles in some ways an @code{if} 2610statement in C, but it is important to understand the difference between 2611them. The condition in an @code{if} statement is tested during the 2612execution of your program. Its purpose is to allow your program to 2613behave differently from run to run, depending on the data it is 2614operating on. The condition in a preprocessing conditional directive is 2615tested when your program is compiled. Its purpose is to allow different 2616code to be included in the program depending on the situation at the 2617time of compilation. 2618 2619However, the distinction is becoming less clear. Modern compilers often 2620do test @code{if} statements when a program is compiled, if their 2621conditions are known not to vary at run time, and eliminate code which 2622can never be executed. If you can count on your compiler to do this, 2623you may find that your program is more readable if you use @code{if} 2624statements with constant conditions (perhaps determined by macros). Of 2625course, you can only use this to exclude code, not type definitions or 2626other preprocessing directives, and you can only do it if the code 2627remains syntactically valid when it is not to be used. 2628 2629GCC version 3 eliminates this kind of never-executed code even when 2630not optimizing. Older versions did it only when optimizing. 2631 2632@menu 2633* Conditional Uses:: 2634* Conditional Syntax:: 2635* Deleted Code:: 2636@end menu 2637 2638@node Conditional Uses 2639@section Conditional Uses 2640 2641There are three general reasons to use a conditional. 2642 2643@itemize @bullet 2644@item 2645A program may need to use different code depending on the machine or 2646operating system it is to run on. In some cases the code for one 2647operating system may be erroneous on another operating system; for 2648example, it might refer to data types or constants that do not exist on 2649the other system. When this happens, it is not enough to avoid 2650executing the invalid code. Its mere presence will cause the compiler 2651to reject the program. With a preprocessing conditional, the offending 2652code can be effectively excised from the program when it is not valid. 2653 2654@item 2655You may want to be able to compile the same source file into two 2656different programs. One version might make frequent time-consuming 2657consistency checks on its intermediate data, or print the values of 2658those data for debugging, and the other not. 2659 2660@item 2661A conditional whose condition is always false is one way to exclude code 2662from the program but keep it as a sort of comment for future reference. 2663@end itemize 2664 2665Simple programs that do not need system-specific logic or complex 2666debugging hooks generally will not need to use preprocessing 2667conditionals. 2668 2669@node Conditional Syntax 2670@section Conditional Syntax 2671 2672@findex #if 2673A conditional in the C preprocessor begins with a @dfn{conditional 2674directive}: @samp{#if}, @samp{#ifdef} or @samp{#ifndef}. 2675 2676@menu 2677* Ifdef:: 2678* If:: 2679* Defined:: 2680* Else:: 2681* Elif:: 2682@end menu 2683 2684@node Ifdef 2685@subsection Ifdef 2686@findex #ifdef 2687@findex #endif 2688 2689The simplest sort of conditional is 2690 2691@example 2692@group 2693#ifdef @var{MACRO} 2694 2695@var{controlled text} 2696 2697#endif /* @var{MACRO} */ 2698@end group 2699@end example 2700 2701@cindex conditional group 2702This block is called a @dfn{conditional group}. @var{controlled text} 2703will be included in the output of the preprocessor if and only if 2704@var{MACRO} is defined. We say that the conditional @dfn{succeeds} if 2705@var{MACRO} is defined, @dfn{fails} if it is not. 2706 2707The @var{controlled text} inside of a conditional can include 2708preprocessing directives. They are executed only if the conditional 2709succeeds. You can nest conditional groups inside other conditional 2710groups, but they must be completely nested. In other words, 2711@samp{#endif} always matches the nearest @samp{#ifdef} (or 2712@samp{#ifndef}, or @samp{#if}). Also, you cannot start a conditional 2713group in one file and end it in another. 2714 2715Even if a conditional fails, the @var{controlled text} inside it is 2716still run through initial transformations and tokenization. Therefore, 2717it must all be lexically valid C@. Normally the only way this matters is 2718that all comments and string literals inside a failing conditional group 2719must still be properly ended. 2720 2721The comment following the @samp{#endif} is not required, but it is a 2722good practice if there is a lot of @var{controlled text}, because it 2723helps people match the @samp{#endif} to the corresponding @samp{#ifdef}. 2724Older programs sometimes put @var{MACRO} directly after the 2725@samp{#endif} without enclosing it in a comment. This is invalid code 2726according to the C standard. GNU CPP accepts it with a warning. It 2727never affects which @samp{#ifndef} the @samp{#endif} matches. 2728 2729@findex #ifndef 2730Sometimes you wish to use some code if a macro is @emph{not} defined. 2731You can do this by writing @samp{#ifndef} instead of @samp{#ifdef}. 2732One common use of @samp{#ifndef} is to include code only the first 2733time a header file is included. @xref{Once-Only Headers}. 2734 2735Macro definitions can vary between compilations for several reasons. 2736Here are some samples. 2737 2738@itemize @bullet 2739@item 2740Some macros are predefined on each kind of machine 2741(@pxref{System-specific Predefined Macros}). This allows you to provide 2742code specially tuned for a particular machine. 2743 2744@item 2745System header files define more macros, associated with the features 2746they implement. You can test these macros with conditionals to avoid 2747using a system feature on a machine where it is not implemented. 2748 2749@item 2750Macros can be defined or undefined with the @option{-D} and @option{-U} 2751command line options when you compile the program. You can arrange to 2752compile the same source file into two different programs by choosing a 2753macro name to specify which program you want, writing conditionals to 2754test whether or how this macro is defined, and then controlling the 2755state of the macro with command line options, perhaps set in the 2756Makefile. @xref{Invocation}. 2757 2758@item 2759Your program might have a special header file (often called 2760@file{config.h}) that is adjusted when the program is compiled. It can 2761define or not define macros depending on the features of the system and 2762the desired capabilities of the program. The adjustment can be 2763automated by a tool such as @command{autoconf}, or done by hand. 2764@end itemize 2765 2766@node If 2767@subsection If 2768 2769The @samp{#if} directive allows you to test the value of an arithmetic 2770expression, rather than the mere existence of one macro. Its syntax is 2771 2772@example 2773@group 2774#if @var{expression} 2775 2776@var{controlled text} 2777 2778#endif /* @var{expression} */ 2779@end group 2780@end example 2781 2782@var{expression} is a C expression of integer type, subject to stringent 2783restrictions. It may contain 2784 2785@itemize @bullet 2786@item 2787Integer constants. 2788 2789@item 2790Character constants, which are interpreted as they would be in normal 2791code. 2792 2793@item 2794Arithmetic operators for addition, subtraction, multiplication, 2795division, bitwise operations, shifts, comparisons, and logical 2796operations (@code{&&} and @code{||}). The latter two obey the usual 2797short-circuiting rules of standard C@. 2798 2799@item 2800Macros. All macros in the expression are expanded before actual 2801computation of the expression's value begins. 2802 2803@item 2804Uses of the @code{defined} operator, which lets you check whether macros 2805are defined in the middle of an @samp{#if}. 2806 2807@item 2808Identifiers that are not macros, which are all considered to be the 2809number zero. This allows you to write @code{@w{#if MACRO}} instead of 2810@code{@w{#ifdef MACRO}}, if you know that MACRO, when defined, will 2811always have a nonzero value. Function-like macros used without their 2812function call parentheses are also treated as zero. 2813 2814In some contexts this shortcut is undesirable. The @option{-Wundef} 2815option causes GCC to warn whenever it encounters an identifier which is 2816not a macro in an @samp{#if}. 2817@end itemize 2818 2819The preprocessor does not know anything about types in the language. 2820Therefore, @code{sizeof} operators are not recognized in @samp{#if}, and 2821neither are @code{enum} constants. They will be taken as identifiers 2822which are not macros, and replaced by zero. In the case of 2823@code{sizeof}, this is likely to cause the expression to be invalid. 2824 2825The preprocessor calculates the value of @var{expression}. It carries 2826out all calculations in the widest integer type known to the compiler; 2827on most machines supported by GCC this is 64 bits. This is not the same 2828rule as the compiler uses to calculate the value of a constant 2829expression, and may give different results in some cases. If the value 2830comes out to be nonzero, the @samp{#if} succeeds and the @var{controlled 2831text} is included; otherwise it is skipped. 2832 2833If @var{expression} is not correctly formed, GCC issues an error and 2834treats the conditional as having failed. 2835 2836@node Defined 2837@subsection Defined 2838 2839@cindex @code{defined} 2840The special operator @code{defined} is used in @samp{#if} and 2841@samp{#elif} expressions to test whether a certain name is defined as a 2842macro. @code{defined @var{name}} and @code{defined (@var{name})} are 2843both expressions whose value is 1 if @var{name} is defined as a macro at 2844the current point in the program, and 0 otherwise. Thus, @code{@w{#if 2845defined MACRO}} is precisely equivalent to @code{@w{#ifdef MACRO}}. 2846 2847@code{defined} is useful when you wish to test more than one macro for 2848existence at once. For example, 2849 2850@example 2851#if defined (__vax__) || defined (__ns16000__) 2852@end example 2853 2854@noindent 2855would succeed if either of the names @code{__vax__} or 2856@code{__ns16000__} is defined as a macro. 2857 2858Conditionals written like this: 2859 2860@example 2861#if defined BUFSIZE && BUFSIZE >= 1024 2862@end example 2863 2864@noindent 2865can generally be simplified to just @code{@w{#if BUFSIZE >= 1024}}, 2866since if @code{BUFSIZE} is not defined, it will be interpreted as having 2867the value zero. 2868 2869If the @code{defined} operator appears as a result of a macro expansion, 2870the C standard says the behavior is undefined. GNU cpp treats it as a 2871genuine @code{defined} operator and evaluates it normally. It will warn 2872wherever your code uses this feature if you use the command-line option 2873@option{-pedantic}, since other compilers may handle it differently. 2874 2875@node Else 2876@subsection Else 2877 2878@findex #else 2879The @samp{#else} directive can be added to a conditional to provide 2880alternative text to be used if the condition fails. This is what it 2881looks like: 2882 2883@example 2884@group 2885#if @var{expression} 2886@var{text-if-true} 2887#else /* Not @var{expression} */ 2888@var{text-if-false} 2889#endif /* Not @var{expression} */ 2890@end group 2891@end example 2892 2893@noindent 2894If @var{expression} is nonzero, the @var{text-if-true} is included and 2895the @var{text-if-false} is skipped. If @var{expression} is zero, the 2896opposite happens. 2897 2898You can use @samp{#else} with @samp{#ifdef} and @samp{#ifndef}, too. 2899 2900@node Elif 2901@subsection Elif 2902 2903@findex #elif 2904One common case of nested conditionals is used to check for more than two 2905possible alternatives. For example, you might have 2906 2907@example 2908#if X == 1 2909@dots{} 2910#else /* X != 1 */ 2911#if X == 2 2912@dots{} 2913#else /* X != 2 */ 2914@dots{} 2915#endif /* X != 2 */ 2916#endif /* X != 1 */ 2917@end example 2918 2919Another conditional directive, @samp{#elif}, allows this to be 2920abbreviated as follows: 2921 2922@example 2923#if X == 1 2924@dots{} 2925#elif X == 2 2926@dots{} 2927#else /* X != 2 and X != 1*/ 2928@dots{} 2929#endif /* X != 2 and X != 1*/ 2930@end example 2931 2932@samp{#elif} stands for ``else if''. Like @samp{#else}, it goes in the 2933middle of a conditional group and subdivides it; it does not require a 2934matching @samp{#endif} of its own. Like @samp{#if}, the @samp{#elif} 2935directive includes an expression to be tested. The text following the 2936@samp{#elif} is processed only if the original @samp{#if}-condition 2937failed and the @samp{#elif} condition succeeds. 2938 2939More than one @samp{#elif} can go in the same conditional group. Then 2940the text after each @samp{#elif} is processed only if the @samp{#elif} 2941condition succeeds after the original @samp{#if} and all previous 2942@samp{#elif} directives within it have failed. 2943 2944@samp{#else} is allowed after any number of @samp{#elif} directives, but 2945@samp{#elif} may not follow @samp{#else}. 2946 2947@node Deleted Code 2948@section Deleted Code 2949@cindex commenting out code 2950 2951If you replace or delete a part of the program but want to keep the old 2952code around for future reference, you often cannot simply comment it 2953out. Block comments do not nest, so the first comment inside the old 2954code will end the commenting-out. The probable result is a flood of 2955syntax errors. 2956 2957One way to avoid this problem is to use an always-false conditional 2958instead. For instance, put @code{#if 0} before the deleted code and 2959@code{#endif} after it. This works even if the code being turned 2960off contains conditionals, but they must be entire conditionals 2961(balanced @samp{#if} and @samp{#endif}). 2962 2963Some people use @code{#ifdef notdef} instead. This is risky, because 2964@code{notdef} might be accidentally defined as a macro, and then the 2965conditional would succeed. @code{#if 0} can be counted on to fail. 2966 2967Do not use @code{#if 0} for comments which are not C code. Use a real 2968comment, instead. The interior of @code{#if 0} must consist of complete 2969tokens; in particular, single-quote characters must balance. Comments 2970often contain unbalanced single-quote characters (known in English as 2971apostrophes). These confuse @code{#if 0}. They don't confuse 2972@samp{/*}. 2973 2974@node Diagnostics 2975@chapter Diagnostics 2976@cindex diagnostic 2977@cindex reporting errors 2978@cindex reporting warnings 2979 2980@findex #error 2981The directive @samp{#error} causes the preprocessor to report a fatal 2982error. The tokens forming the rest of the line following @samp{#error} 2983are used as the error message. 2984 2985You would use @samp{#error} inside of a conditional that detects a 2986combination of parameters which you know the program does not properly 2987support. For example, if you know that the program will not run 2988properly on a VAX, you might write 2989 2990@example 2991@group 2992#ifdef __vax__ 2993#error "Won't work on VAXen. See comments at get_last_object." 2994#endif 2995@end group 2996@end example 2997 2998If you have several configuration parameters that must be set up by 2999the installation in a consistent way, you can use conditionals to detect 3000an inconsistency and report it with @samp{#error}. For example, 3001 3002@example 3003#if !defined(UNALIGNED_INT_ASM_OP) && defined(DWARF2_DEBUGGING_INFO) 3004#error "DWARF2_DEBUGGING_INFO requires UNALIGNED_INT_ASM_OP." 3005#endif 3006@end example 3007 3008@findex #warning 3009The directive @samp{#warning} is like @samp{#error}, but causes the 3010preprocessor to issue a warning and continue preprocessing. The tokens 3011following @samp{#warning} are used as the warning message. 3012 3013You might use @samp{#warning} in obsolete header files, with a message 3014directing the user to the header file which should be used instead. 3015 3016Neither @samp{#error} nor @samp{#warning} macro-expands its argument. 3017Internal whitespace sequences are each replaced with a single space. 3018The line must consist of complete tokens. It is wisest to make the 3019argument of these directives be a single string constant; this avoids 3020problems with apostrophes and the like. 3021 3022@node Line Control 3023@chapter Line Control 3024@cindex line control 3025 3026The C preprocessor informs the C compiler of the location in your source 3027code where each token came from. Presently, this is just the file name 3028and line number. All the tokens resulting from macro expansion are 3029reported as having appeared on the line of the source file where the 3030outermost macro was used. We intend to be more accurate in the future. 3031 3032If you write a program which generates source code, such as the 3033@command{bison} parser generator, you may want to adjust the preprocessor's 3034notion of the current file name and line number by hand. Parts of the 3035output from @command{bison} are generated from scratch, other parts come 3036from a standard parser file. The rest are copied verbatim from 3037@command{bison}'s input. You would like compiler error messages and 3038symbolic debuggers to be able to refer to @code{bison}'s input file. 3039 3040@findex #line 3041@command{bison} or any such program can arrange this by writing 3042@samp{#line} directives into the output file. @samp{#line} is a 3043directive that specifies the original line number and source file name 3044for subsequent input in the current preprocessor input file. 3045@samp{#line} has three variants: 3046 3047@table @code 3048@item #line @var{linenum} 3049@var{linenum} is a non-negative decimal integer constant. It specifies 3050the line number which should be reported for the following line of 3051input. Subsequent lines are counted from @var{linenum}. 3052 3053@item #line @var{linenum} @var{filename} 3054@var{linenum} is the same as for the first form, and has the same 3055effect. In addition, @var{filename} is a string constant. The 3056following line and all subsequent lines are reported to come from the 3057file it specifies, until something else happens to change that. 3058@var{filename} is interpreted according to the normal rules for a string 3059constant: backslash escapes are interpreted. This is different from 3060@samp{#include}. 3061 3062Previous versions of GNU CPP did not interpret escapes in @samp{#line}; 3063we have changed it because the standard requires they be interpreted, 3064and most other compilers do. 3065 3066@item #line @var{anything else} 3067@var{anything else} is checked for macro calls, which are expanded. 3068The result should match one of the above two forms. 3069@end table 3070 3071@samp{#line} directives alter the results of the @code{__FILE__} and 3072@code{__LINE__} predefined macros from that point on. @xref{Standard 3073Predefined Macros}. They do not have any effect on @samp{#include}'s 3074idea of the directory containing the current file. This is a change 3075from GCC 2.95. Previously, a file reading 3076 3077@smallexample 3078#line 1 "../src/gram.y" 3079#include "gram.h" 3080@end smallexample 3081 3082would search for @file{gram.h} in @file{../src}, then the @option{-I} 3083chain; the directory containing the physical source file would not be 3084searched. In GCC 3.0 and later, the @samp{#include} is not affected by 3085the presence of a @samp{#line} referring to a different directory. 3086 3087We made this change because the old behavior caused problems when 3088generated source files were transported between machines. For instance, 3089it is common practice to ship generated parsers with a source release, 3090so that people building the distribution do not need to have yacc or 3091Bison installed. These files frequently have @samp{#line} directives 3092referring to the directory tree of the system where the distribution was 3093created. If GCC tries to search for headers in those directories, the 3094build is likely to fail. 3095 3096The new behavior can cause failures too, if the generated file is not 3097in the same directory as its source and it attempts to include a header 3098which would be visible searching from the directory containing the 3099source file. However, this problem is easily solved with an additional 3100@option{-I} switch on the command line. The failures caused by the old 3101semantics could sometimes be corrected only by editing the generated 3102files, which is difficult and error-prone. 3103 3104@node Pragmas 3105@chapter Pragmas 3106 3107The @samp{#pragma} directive is the method specified by the C standard 3108for providing additional information to the compiler, beyond what is 3109conveyed in the language itself. Three forms of this directive 3110(commonly known as @dfn{pragmas}) are specified by the 1999 C standard. 3111A C compiler is free to attach any meaning it likes to other pragmas. 3112 3113GCC has historically preferred to use extensions to the syntax of the 3114language, such as @code{__attribute__}, for this purpose. However, GCC 3115does define a few pragmas of its own. These mostly have effects on the 3116entire translation unit or source file. 3117 3118In GCC version 3, all GNU-defined, supported pragmas have been given a 3119@code{GCC} prefix. This is in line with the @code{STDC} prefix on all 3120pragmas defined by C99. For backward compatibility, pragmas which were 3121recognized by previous versions are still recognized without the 3122@code{GCC} prefix, but that usage is deprecated. Some older pragmas are 3123deprecated in their entirety. They are not recognized with the 3124@code{GCC} prefix. @xref{Obsolete Features}. 3125 3126@cindex @code{_Pragma} 3127C99 introduces the @code{@w{_Pragma}} operator. This feature addresses a 3128major problem with @samp{#pragma}: being a directive, it cannot be 3129produced as the result of macro expansion. @code{@w{_Pragma}} is an 3130operator, much like @code{sizeof} or @code{defined}, and can be embedded 3131in a macro. 3132 3133Its syntax is @code{@w{_Pragma (@var{string-literal})}}, where 3134@var{string-literal} can be either a normal or wide-character string 3135literal. It is destringized, by replacing all @samp{\\} with a single 3136@samp{\} and all @samp{\"} with a @samp{"}. The result is then 3137processed as if it had appeared as the right hand side of a 3138@samp{#pragma} directive. For example, 3139 3140@example 3141_Pragma ("GCC dependency \"parse.y\"") 3142@end example 3143 3144@noindent 3145has the same effect as @code{#pragma GCC dependency "parse.y"}. The 3146same effect could be achieved using macros, for example 3147 3148@example 3149#define DO_PRAGMA(x) _Pragma (#x) 3150DO_PRAGMA (GCC dependency "parse.y") 3151@end example 3152 3153The standard is unclear on where a @code{_Pragma} operator can appear. 3154The preprocessor does not accept it within a preprocessing conditional 3155directive like @samp{#if}. To be safe, you are probably best keeping it 3156out of directives other than @samp{#define}, and putting it on a line of 3157its own. 3158 3159This manual documents the pragmas which are meaningful to the 3160preprocessor itself. Other pragmas are meaningful to the C or C++ 3161compilers. They are documented in the GCC manual. 3162 3163@ftable @code 3164@item #pragma GCC dependency 3165@code{#pragma GCC dependency} allows you to check the relative dates of 3166the current file and another file. If the other file is more recent than 3167the current file, a warning is issued. This is useful if the current 3168file is derived from the other file, and should be regenerated. The 3169other file is searched for using the normal include search path. 3170Optional trailing text can be used to give more information in the 3171warning message. 3172 3173@example 3174#pragma GCC dependency "parse.y" 3175#pragma GCC dependency "/usr/include/time.h" rerun fixincludes 3176@end example 3177 3178@item #pragma GCC poison 3179Sometimes, there is an identifier that you want to remove completely 3180from your program, and make sure that it never creeps back in. To 3181enforce this, you can @dfn{poison} the identifier with this pragma. 3182@code{#pragma GCC poison} is followed by a list of identifiers to 3183poison. If any of those identifiers appears anywhere in the source 3184after the directive, it is a hard error. For example, 3185 3186@example 3187#pragma GCC poison printf sprintf fprintf 3188sprintf(some_string, "hello"); 3189@end example 3190 3191@noindent 3192will produce an error. 3193 3194If a poisoned identifier appears as part of the expansion of a macro 3195which was defined before the identifier was poisoned, it will @emph{not} 3196cause an error. This lets you poison an identifier without worrying 3197about system headers defining macros that use it. 3198 3199For example, 3200 3201@example 3202#define strrchr rindex 3203#pragma GCC poison rindex 3204strrchr(some_string, 'h'); 3205@end example 3206 3207@noindent 3208will not produce an error. 3209 3210@item #pragma GCC system_header 3211This pragma takes no arguments. It causes the rest of the code in the 3212current file to be treated as if it came from a system header. 3213@xref{System Headers}. 3214 3215@end ftable 3216 3217@node Other Directives 3218@chapter Other Directives 3219 3220@findex #ident 3221The @samp{#ident} directive takes one argument, a string constant. On 3222some systems, that string constant is copied into a special segment of 3223the object file. On other systems, the directive is ignored. 3224 3225This directive is not part of the C standard, but it is not an official 3226GNU extension either. We believe it came from System V@. 3227 3228@findex #sccs 3229The @samp{#sccs} directive is recognized on some systems, because it 3230appears in their header files. It is a very old, obscure, extension 3231which we did not invent, and we have been unable to find any 3232documentation of what it should do, so GCC simply ignores it. 3233 3234@cindex null directive 3235The @dfn{null directive} consists of a @samp{#} followed by a newline, 3236with only whitespace (including comments) in between. A null directive 3237is understood as a preprocessing directive but has no effect on the 3238preprocessor output. The primary significance of the existence of the 3239null directive is that an input line consisting of just a @samp{#} will 3240produce no output, rather than a line of output containing just a 3241@samp{#}. Supposedly some old C programs contain such lines. 3242 3243@node Preprocessor Output 3244@chapter Preprocessor Output 3245 3246When the C preprocessor is used with the C, C++, or Objective-C 3247compilers, it is integrated into the compiler and communicates a stream 3248of binary tokens directly to the compiler's parser. However, it can 3249also be used in the more conventional standalone mode, where it produces 3250textual output. 3251@c FIXME: Document the library interface. 3252 3253@cindex output format 3254The output from the C preprocessor looks much like the input, except 3255that all preprocessing directive lines have been replaced with blank 3256lines and all comments with spaces. Long runs of blank lines are 3257discarded. 3258 3259The ISO standard specifies that it is implementation defined whether a 3260preprocessor preserves whitespace between tokens, or replaces it with 3261e.g.@: a single space. In GNU CPP, whitespace between tokens is collapsed 3262to become a single space, with the exception that the first token on a 3263non-directive line is preceded with sufficient spaces that it appears in 3264the same column in the preprocessed output that it appeared in the 3265original source file. This is so the output is easy to read. 3266@xref{Differences from previous versions}. CPP does not insert any 3267whitespace where there was none in the original source, except where 3268necessary to prevent an accidental token paste. 3269 3270@cindex linemarkers 3271Source file name and line number information is conveyed by lines 3272of the form 3273 3274@example 3275# @var{linenum} @var{filename} @var{flags} 3276@end example 3277 3278@noindent 3279These are called @dfn{linemarkers}. They are inserted as needed into 3280the output (but never within a string or character constant). They mean 3281that the following line originated in file @var{filename} at line 3282@var{linenum}. @var{filename} will never contain any non-printing 3283characters; they are replaced with octal escape sequences. 3284 3285After the file name comes zero or more flags, which are @samp{1}, 3286@samp{2}, @samp{3}, or @samp{4}. If there are multiple flags, spaces 3287separate them. Here is what the flags mean: 3288 3289@table @samp 3290@item 1 3291This indicates the start of a new file. 3292@item 2 3293This indicates returning to a file (after having included another file). 3294@item 3 3295This indicates that the following text comes from a system header file, 3296so certain warnings should be suppressed. 3297@item 4 3298This indicates that the following text should be treated as being 3299wrapped in an implicit @code{extern "C"} block. 3300@c maybe cross reference NO_IMPLICIT_EXTERN_C 3301@end table 3302 3303As an extension, the preprocessor accepts linemarkers in non-assembler 3304input files. They are treated like the corresponding @samp{#line} 3305directive, (@pxref{Line Control}), except that trailing flags are 3306permitted, and are interpreted with the meanings described above. If 3307multiple flags are given, they must be in ascending order. 3308 3309Some directives may be duplicated in the output of the preprocessor. 3310These are @samp{#ident} (always), @samp{#pragma} (only if the 3311preprocessor does not handle the pragma itself), and @samp{#define} and 3312@samp{#undef} (with certain debugging options). If this happens, the 3313@samp{#} of the directive will always be in the first column, and there 3314will be no space between the @samp{#} and the directive name. If macro 3315expansion happens to generate tokens which might be mistaken for a 3316duplicated directive, a space will be inserted between the @samp{#} and 3317the directive name. 3318 3319@node Traditional Mode 3320@chapter Traditional Mode 3321 3322Traditional (pre-standard) C preprocessing is rather different from 3323the preprocessing specified by the standard. When GCC is given the 3324@option{-traditional} option, it attempts to emulate a traditional 3325preprocessor. We do not guarantee that GCC's behavior under 3326@option{-traditional} matches any pre-standard preprocessor exactly. 3327 3328Traditional mode exists only for backward compatibility. We have no 3329plans to augment it in any way nor will we change it except to fix 3330catastrophic bugs. You should be aware that modern C libraries often 3331have header files which are incompatible with traditional mode. 3332 3333This is a list of the differences. It may not be complete, and may not 3334correspond exactly to the behavior of either GCC or a true traditional 3335preprocessor. 3336 3337@itemize @bullet 3338@item 3339Traditional macro expansion pays no attention to single-quote or 3340double-quote characters; macro argument symbols are replaced by the 3341argument values even when they appear within apparent string or 3342character constants. 3343 3344@item 3345Traditionally, it is permissible for a macro expansion to end in the 3346middle of a string or character constant. The constant continues into 3347the text surrounding the macro call. 3348 3349@item 3350However, the end of the line terminates a string or character constant, 3351with no error. (This is a kluge. Traditional mode is commonly used to 3352preprocess things which are not C, and have a different comment syntax. 3353Single apostrophes often appear in comments. This kluge prevents the 3354traditional preprocessor from issuing errors on such comments.) 3355 3356@item 3357Preprocessing directives are recognized in traditional C only when their 3358leading @samp{#} appears in the first column. There can be no 3359whitespace between the beginning of the line and the @samp{#}. 3360 3361@item 3362In traditional C, a comment is equivalent to no text at all. (In ISO 3363C, a comment counts as whitespace.) It can be used sort of the same way 3364that @samp{##} is used in ISO C, to paste macro arguments together. 3365 3366@item 3367Traditional C does not have the concept of a preprocessing number. 3368 3369@item 3370A macro is not suppressed within its own definition, in traditional C@. 3371Thus, any macro that is used recursively inevitably causes an error. 3372 3373@item 3374The @samp{#} and @samp{##} operators are not available in traditional 3375C@. 3376 3377@item 3378In traditional C, the text at the end of a macro expansion can run 3379together with the text after the macro call, to produce a single token. 3380This is impossible in ISO C@. 3381 3382@item 3383None of the GNU extensions to the preprocessor are available in 3384traditional mode, with the exception of a partial implementation of 3385assertions, and those may be removed in the future. 3386 3387@item 3388A true traditional C preprocessor does not recognize @samp{#elif}, 3389@samp{#error}, or @samp{#pragma}. GCC supports @samp{#elif} and 3390@samp{#error} even in traditional mode, but not @samp{#pragma}. 3391 3392@item 3393Traditional mode is text-based, not token-based, and comments are 3394stripped after macro expansion. Therefore, @samp{/**/} can be used to 3395paste tokens together provided that there is no whitespace between it 3396and the tokens to be pasted. 3397 3398@item 3399Traditional mode preserves the amount and form of whitespace provided by 3400the user. Hard tabs remain hard tabs. This can be useful, e.g.@: if you 3401are preprocessing a Makefile (which we do not encourage). 3402@end itemize 3403 3404You can request warnings about features that did not exist, or worked 3405differently, in traditional C with the @option{-Wtraditional} option. 3406This works only if you do @emph{not} specify @option{-traditional}. GCC 3407does not warn about features of ISO C which you must use when you are 3408using a conforming compiler, such as the @samp{#} and @samp{##} 3409operators. 3410 3411Presently @option{-Wtraditional} warns about: 3412 3413@itemize @bullet 3414@item 3415Macro parameters that appear within string literals in the macro body. 3416In traditional C macro replacement takes place within string literals, 3417but does not in ISO C@. 3418 3419@item 3420In traditional C, some preprocessor directives did not exist. 3421Traditional preprocessors would only consider a line to be a directive 3422if the @samp{#} appeared in column 1 on the line. Therefore 3423@option{-Wtraditional} warns about directives that traditional C 3424understands but would ignore because the @samp{#} does not appear as the 3425first character on the line. It also suggests you hide directives like 3426@samp{#pragma} not understood by traditional C by indenting them. Some 3427traditional implementations would not recognize @samp{#elif}, so it 3428suggests avoiding it altogether. 3429 3430@item 3431A function-like macro that appears without an argument list. In 3432traditional C this was an error. In ISO C it merely means that the 3433macro is not expanded. 3434 3435@item 3436The unary plus operator. This did not exist in traditional C@. 3437 3438@item 3439The @samp{U} and @samp{LL} integer constant suffixes, which were not 3440available in traditional C@. (Traditional C does support the @samp{L} 3441suffix for simple long integer constants.) You are not warned about 3442uses of these suffixes in macros defined in system headers. For 3443instance, @code{UINT_MAX} may well be defined as @code{4294967295U}, but 3444you will not be warned if you use @code{UINT_MAX}. 3445 3446You can usually avoid the warning, and the related warning about 3447constants which are so large that they are unsigned, by writing the 3448integer constant in question in hexadecimal, with no U suffix. Take 3449care, though, because this gives the wrong result in exotic cases. 3450@end itemize 3451 3452@node Implementation Details 3453@chapter Implementation Details 3454 3455Here we document details of how the preprocessor's implementation 3456affects its user-visible behavior. You should try to avoid undue 3457reliance on behavior described here, as it is possible that it will 3458change subtly in future implementations. 3459 3460Also documented here are obsolete features and changes from previous 3461versions of GNU CPP@. 3462 3463@menu 3464* Implementation-defined behavior:: 3465* Implementation limits:: 3466* Obsolete Features:: 3467* Differences from previous versions:: 3468@end menu 3469 3470@node Implementation-defined behavior 3471@section Implementation-defined behavior 3472@cindex implementation-defined behavior 3473 3474This is how GNU CPP behaves in all the cases which the C standard 3475describes as @dfn{implementation-defined}. This term means that the 3476implementation is free to do what it likes, but must document its choice 3477and stick to it. 3478@c FIXME: Check the C++ standard for more implementation-defined stuff. 3479 3480@itemize @bullet 3481@need 1000 3482@item The mapping of physical source file multi-byte characters to the 3483execution character set. 3484 3485Currently, GNU cpp only supports character sets that are strict supersets 3486of ASCII, and performs no translation of characters. 3487 3488@item Non-empty sequences of whitespace characters. 3489 3490In textual output, each whitespace sequence is collapsed to a single 3491space. For aesthetic reasons, the first token on each non-directive 3492line of output is preceded with sufficient spaces that it appears in the 3493same column as it did in the original source file. 3494 3495@item The numeric value of character constants in preprocessor expressions. 3496 3497The preprocessor and compiler interpret character constants in the same 3498way; escape sequences such as @samp{\a} are given the values they would 3499have on the target machine. 3500 3501Multi-character character constants are interpreted a character at a 3502time, shifting the previous result left by the number of bits per 3503character on the host, and adding the new character. For example, 'ab' 3504on an 8-bit host would be interpreted as @w{'a' * 256 + 'b'}. If there 3505are more characters in the constant than can fit in the widest native 3506integer type on the host, usually a @code{long}, the excess characters 3507are ignored and a diagnostic is given. 3508 3509@item Source file inclusion. 3510 3511For a discussion on how the preprocessor locates header files, 3512@ref{Include Operation}. 3513 3514@item Interpretation of the filename resulting from a macro-expanded 3515@samp{#include} directive. 3516 3517@xref{Computed Includes}. 3518 3519@item Treatment of a @samp{#pragma} directive that after macro-expansion 3520results in a standard pragma. 3521 3522No macro expansion occurs on any @samp{#pragma} directive line, so the 3523question does not arise. 3524 3525Note that GCC does not yet implement any of the standard 3526pragmas. 3527 3528@end itemize 3529 3530@node Implementation limits 3531@section Implementation limits 3532@cindex implementation limits 3533 3534GNU CPP has a small number of internal limits. This section lists the 3535limits which the C standard requires to be no lower than some minimum, 3536and all the others we are aware of. We intend there to be as few limits 3537as possible. If you encounter an undocumented or inconvenient limit, 3538please report that to us as a bug. (See the section on reporting bugs in 3539the GCC manual.) 3540 3541Where we say something is limited @dfn{only by available memory}, that 3542means that internal data structures impose no intrinsic limit, and space 3543is allocated with @code{malloc} or equivalent. The actual limit will 3544therefore depend on many things, such as the size of other things 3545allocated by the compiler at the same time, the amount of memory 3546consumed by other processes on the same computer, etc. 3547 3548@itemize @bullet 3549 3550@item Nesting levels of @samp{#include} files. 3551 3552We impose an arbitrary limit of 200 levels, to avoid runaway recursion. 3553The standard requires at least 15 levels. 3554 3555@item Nesting levels of conditional inclusion. 3556 3557The C standard mandates this be at least 63. GNU CPP is limited only by 3558available memory. 3559 3560@item Levels of parenthesised expressions within a full expression. 3561 3562The C standard requires this to be at least 63. In preprocessor 3563conditional expressions, it is limited only by available memory. 3564 3565@item Significant initial characters in an identifier or macro name. 3566 3567The preprocessor treats all characters as significant. The C standard 3568requires only that the first 63 be significant. 3569 3570@item Number of macros simultaneously defined in a single translation unit. 3571 3572The standard requires at least 4095 be possible. GNU CPP is limited only 3573by available memory. 3574 3575@item Number of parameters in a macro definition and arguments in a macro call. 3576 3577We allow @code{USHRT_MAX}, which is no smaller than 65,535. The minimum 3578required by the standard is 127. 3579 3580@item Number of characters on a logical source line. 3581 3582The C standard requires a minimum of 4096 be permitted. GNU CPP places 3583no limits on this, but you may get incorrect column numbers reported in 3584diagnostics for lines longer than 65,535 characters. 3585 3586@item Maximum size of a source file. 3587 3588The standard does not specify any lower limit on the maximum size of a 3589source file. GNU cpp maps files into memory, so it is limited by the 3590available address space. This is generally at least two gigabytes. 3591Depending on the operating system, the size of physical memory may or 3592may not be a limitation. 3593 3594@end itemize 3595 3596@node Obsolete Features 3597@section Obsolete Features 3598 3599GNU CPP has a number of features which are present mainly for 3600compatibility with older programs. We discourage their use in new code. 3601In some cases, we plan to remove the feature in a future version of GCC@. 3602 3603@menu 3604* Assertions:: 3605* Obsolete once-only headers:: 3606* Miscellaneous obsolete features:: 3607@end menu 3608 3609@node Assertions 3610@subsection Assertions 3611@cindex assertions 3612 3613@dfn{Assertions} are a deprecated alternative to macros in writing 3614conditionals to test what sort of computer or system the compiled 3615program will run on. Assertions are usually predefined, but you can 3616define them with preprocessing directives or command-line options. 3617 3618Assertions were intended to provide a more systematic way to describe 3619the compiler's target system. However, in practice they are just as 3620unpredictable as the system-specific predefined macros. In addition, they 3621are not part of any standard, and only a few compilers support them. 3622Therefore, the use of assertions is @strong{less} portable than the use 3623of system-specific predefined macros. We recommend you do not use them at 3624all. 3625 3626@cindex predicates 3627An assertion looks like this: 3628 3629@example 3630#@var{predicate} (@var{answer}) 3631@end example 3632 3633@noindent 3634@var{predicate} must be a single identifier. @var{answer} can be any 3635sequence of tokens; all characters are significant except for leading 3636and trailing whitespace, and differences in internal whitespace 3637sequences are ignored. (This is similar to the rules governing macro 3638redefinition.) Thus, @code{(x + y)} is different from @code{(x+y)} but 3639equivalent to @code{@w{( x + y )}}. Parentheses do not nest inside an 3640answer. 3641 3642@cindex testing predicates 3643To test an assertion, you write it in an @samp{#if}. For example, this 3644conditional succeeds if either @code{vax} or @code{ns16000} has been 3645asserted as an answer for @code{machine}. 3646 3647@example 3648#if #machine (vax) || #machine (ns16000) 3649@end example 3650 3651@noindent 3652You can test whether @emph{any} answer is asserted for a predicate by 3653omitting the answer in the conditional: 3654 3655@example 3656#if #machine 3657@end example 3658 3659@findex #assert 3660Assertions are made with the @samp{#assert} directive. Its sole 3661argument is the assertion to make, without the leading @samp{#} that 3662identifies assertions in conditionals. 3663 3664@example 3665#assert @var{predicate} (@var{answer}) 3666@end example 3667 3668@noindent 3669You may make several assertions with the same predicate and different 3670answers. Subsequent assertions do not override previous ones for the 3671same predicate. All the answers for any given predicate are 3672simultaneously true. 3673 3674@cindex assertions, cancelling 3675@findex #unassert 3676Assertions can be cancelled with the @samp{#unassert} directive. It 3677has the same syntax as @samp{#assert}. In that form it cancels only the 3678answer which was specified on the @samp{#unassert} line; other answers 3679for that predicate remain true. You can cancel an entire predicate by 3680leaving out the answer: 3681 3682@example 3683#unassert @var{predicate} 3684@end example 3685 3686@noindent 3687In either form, if no such assertion has been made, @samp{#unassert} has 3688no effect. 3689 3690You can also make or cancel assertions using command line options. 3691@xref{Invocation}. 3692 3693@node Obsolete once-only headers 3694@subsection Obsolete once-only headers 3695 3696GNU CPP supports two more ways of indicating that a header file should be 3697read only once. Neither one is as portable as a wrapper @samp{#ifndef}, 3698and we recommend you do not use them in new programs. 3699 3700@findex #import 3701In the Objective-C language, there is a variant of @samp{#include} 3702called @samp{#import} which includes a file, but does so at most once. 3703If you use @samp{#import} instead of @samp{#include}, then you don't 3704need the conditionals inside the header file to prevent multiple 3705inclusion of the contents. GCC permits the use of @samp{#import} in C 3706and C++ as well as Objective-C@. However, it is not in standard C or C++ 3707and should therefore not be used by portable programs. 3708 3709@samp{#import} is not a well designed feature. It requires the users of 3710a header file to know that it should only be included once. It is much 3711better for the header file's implementor to write the file so that users 3712don't need to know this. Using a wrapper @samp{#ifndef} accomplishes 3713this goal. 3714 3715In the present implementation, a single use of @samp{#import} will 3716prevent the file from ever being read again, by either @samp{#import} or 3717@samp{#include}. You should not rely on this; do not use both 3718@samp{#import} and @samp{#include} to refer to the same header file. 3719 3720Another way to prevent a header file from being included more than once 3721is with the @samp{#pragma once} directive. If @samp{#pragma once} is 3722seen when scanning a header file, that file will never be read again, no 3723matter what. 3724 3725@samp{#pragma once} does not have the problems that @samp{#import} does, 3726but it is not recognized by all preprocessors, so you cannot rely on it 3727in a portable program. 3728 3729@node Miscellaneous obsolete features 3730@subsection Miscellaneous obsolete features 3731 3732Here are a few more obsolete features. 3733 3734@itemize @bullet 3735@cindex invalid token paste 3736@item Attempting to paste two tokens which together do not form a valid 3737preprocessing token. 3738 3739The preprocessor currently warns about this, and the resulting 3740preprocessed output is undefined. The tokens remain distinct if the 3741preprocessor is being used directly by the compiler front end. 3742 3743Most of the time, when you get this warning, you will find that @samp{##} 3744is being used superstitiously, to guard against whitespace appearing 3745between two tokens. It is almost always safe to delete the @samp{##}. 3746 3747@cindex pragma poison 3748@item @code{#pragma poison} 3749 3750This is the same as @code{#pragma GCC poison}. The version without the 3751@code{GCC} prefix is deprecated. @xref{Pragmas}. 3752 3753@cindex multi-line string constants 3754@item Multi-line string constants 3755 3756GCC currently allows a string constant to extend across multiple logical 3757lines of the source file. This extension is deprecated and will be 3758removed in a future version of GCC@. Such string constants are already 3759rejected in all directives apart from @samp{#define}. 3760 3761Instead, make use of ISO C concatenation of adjacent string literals, or 3762use @samp{\n} followed by a backslash-newline. 3763 3764@end itemize 3765 3766@node Differences from previous versions 3767@section Differences from previous versions 3768@cindex differences from previous versions 3769 3770This section details behavior which has changed from previous versions 3771of GNU CPP@. We do not plan to change it again in the near future, but 3772we do not promise not to, either. 3773 3774The ``previous versions'' discussed here are 2.95 and before. The 3775behavior of GCC 3.0 is mostly the same as the behavior of the widely 3776used 2.96 and 2.97 development snapshots. Where there are differences, 3777they generally represent bugs in the snapshots. 3778 3779@itemize @bullet 3780 3781@item Order of evaluation of @samp{#} and @samp{##} operators 3782 3783The standard does not specify the order of evaluation of a chain of 3784@samp{##} operators, nor whether @samp{#} is evaluated before, after, or 3785at the same time as @samp{##}. You should therefore not write any code 3786which depends on any specific ordering. It is possible to guarantee an 3787ordering, if you need one, by suitable use of nested macros. 3788 3789An example of where this might matter is pasting the arguments @samp{1}, 3790@samp{e} and @samp{-2}. This would be fine for left-to-right pasting, 3791but right-to-left pasting would produce an invalid token @samp{e-2}. 3792 3793GCC 3.0 evaluates @samp{#} and @samp{##} at the same time and strictly 3794left to right. Older versions evaluated all @samp{#} operators first, 3795then all @samp{##} operators, in an unreliable order. 3796 3797@item The form of whitespace betwen tokens in preprocessor output 3798 3799@xref{Preprocessor Output}, for the current textual format. This is 3800also the format used by stringification. Normally, the preprocessor 3801communicates tokens directly to the compiler's parser, and whitespace 3802does not come up at all. 3803 3804Older versions of GCC preserved all whitespace provided by the user and 3805inserted lots more whitespace of their own, because they could not 3806accurately predict when extra spaces were needed to prevent accidental 3807token pasting. 3808 3809@item Optional argument when invoking rest argument macros 3810 3811As an extension, GCC permits you to omit the variable arguments entirely 3812when you use a variable argument macro. This is forbidden by the 1999 C 3813standard, and will provoke a pedantic warning with GCC 3.0. Previous 3814versions accepted it silently. 3815 3816@item @samp{##} swallowing preceding text in rest argument macros 3817 3818Formerly, in a macro expansion, if @samp{##} appeared before a variable 3819arguments parameter, and the set of tokens specified for that argument 3820in the macro invocation was empty, previous versions of GNU CPP would 3821back up and remove the preceding sequence of non-whitespace characters 3822(@strong{not} the preceding token). This extension is in direct 3823conflict with the 1999 C standard and has been drastically pared back. 3824 3825In the current version of the preprocessor, if @samp{##} appears between 3826a comma and a variable arguments parameter, and the variable argument is 3827omitted entirely, the comma will be removed from the expansion. If the 3828variable argument is empty, or the token before @samp{##} is not a 3829comma, then @samp{##} behaves as a normal token paste. 3830 3831@item Traditional mode and GNU extensions 3832 3833Traditional mode used to be implemented in the same program as normal 3834preprocessing. Therefore, all the GNU extensions to the preprocessor 3835were still available in traditional mode. It is now a separate program 3836and does not implement any of the GNU extensions, except for a partial 3837implementation of assertions. Even those may be removed in a future 3838release. 3839 3840@item @samp{#line} and @samp{#include} 3841 3842The @samp{#line} directive used to change GCC's notion of the 3843``directory containing the current file,'' used by @samp{#include} with 3844a double-quoted header file name. In 3.0 and later, it does not. 3845@xref{Line Control}, for further explanation. 3846 3847@item Syntax of @samp{#line} 3848 3849In GCC 2.95 and previous, the string constant argument to @samp{#line} 3850was treated the same way as the argument to @samp{#include}: backslash 3851escapes were not honored, and the string ended at the second @samp{"}. 3852This is not compliant with the C standard. In GCC 3.0, an attempt was 3853made to correct the behavior, so that the string was treated as a real 3854string constant, but it turned out to be buggy. In 3.1, the bugs have 3855been fixed. (We are not fixing the bugs in 3.0 because they affect 3856relatively few people and the fix is quite invasive.) 3857 3858@end itemize 3859 3860@node Invocation 3861@chapter Invocation 3862@cindex invocation 3863@cindex command line 3864 3865Most often when you use the C preprocessor you will not have to invoke it 3866explicitly: the C compiler will do so automatically. However, the 3867preprocessor is sometimes useful on its own. All the options listed 3868here are also acceptable to the C compiler and have the same meaning, 3869except that the C compiler has different rules for specifying the output 3870file. 3871 3872@strong{Note:} Whether you use the preprocessor by way of @command{gcc} 3873or @command{cpp}, the @dfn{compiler driver} is run first. This 3874program's purpose is to translate your command into invocations of the 3875programs that do the actual work. Their command line interfaces are 3876similar but not identical to the documented interface, and may change 3877without notice. 3878 3879@ignore 3880@c man begin SYNOPSIS 3881cpp [@option{-D}@var{macro}[=@var{defn}]@dots{}] [@option{-U}@var{macro}] 3882 [@option{-I}@var{dir}@dots{}] [@option{-W}@var{warn}@dots{}] 3883 [@option{-M}|@option{-MM}] [@option{-MG}] [@option{-MF} @var{filename}] 3884 [@option{-MP}] [@option{-MQ} @var{target}@dots{}] [@option{-MT} @var{target}@dots{}] 3885 [@option{-x} @var{language}] [@option{-std=}@var{standard}] 3886 @var{infile} @var{outfile} 3887 3888Only the most useful options are listed here; see below for the remainder. 3889@c man end 3890@c man begin SEEALSO 3891gpl(7), gfdl(7), fsf-funding(7), 3892gcc(1), as(1), ld(1), and the Info entries for @file{cpp}, @file{gcc}, and 3893@file{binutils}. 3894@c man end 3895@end ignore 3896 3897@c man begin OPTIONS 3898The C preprocessor expects two file names as arguments, @var{infile} and 3899@var{outfile}. The preprocessor reads @var{infile} together with any 3900other files it specifies with @samp{#include}. All the output generated 3901by the combined input files is written in @var{outfile}. 3902 3903Either @var{infile} or @var{outfile} may be @option{-}, which as 3904@var{infile} means to read from standard input and as @var{outfile} 3905means to write to standard output. Also, if either file is omitted, it 3906means the same as if @option{-} had been specified for that file. 3907 3908Unless otherwise noted, or the option ends in @samp{=}, all options 3909which take an argument may have that argument appear either immediately 3910after the option, or with a space between option and argument: 3911@option{-Ifoo} and @option{-I foo} have the same effect. 3912 3913@cindex grouping options 3914@cindex options, grouping 3915Many options have multi-letter names; therefore multiple single-letter 3916options may @emph{not} be grouped: @option{-dM} is very different from 3917@w{@samp{-d -M}}. 3918 3919@cindex options 3920@include cppopts.texi 3921@c man end 3922 3923@node Environment Variables 3924@chapter Environment Variables 3925@cindex environment variables 3926@c man begin ENVIRONMENT 3927 3928This section describes the environment variables that affect how CPP 3929operates. You can use them to specify directories or prefixes to use 3930when searching for include files, or to control dependency output. 3931 3932Note that you can also specify places to search using options such as 3933@option{-I}, and control dependency output with options like 3934@option{-M} (@pxref{Invocation}). These take precedence over 3935environment variables, which in turn take precedence over the 3936configuration of GCC@. 3937 3938@include cppenv.texi 3939@c man end 3940 3941@include fdl.texi 3942 3943@page 3944@node Option Index 3945@unnumbered Option Index 3946 3947CPP's command line options are indexed here without any initial 3948@samp{-} or @samp{--}. 3949 3950@printindex op 3951 3952@node Index of Directives 3953@unnumbered Index of Directives 3954@printindex fn 3955 3956@node Concept Index 3957@unnumbered Concept Index 3958@printindex cp 3959 3960@bye 3961