cpp.texi 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523
  1. @c Copyright @copyright{} 2022 Richard Stallman and Free Software Foundation, Inc.
  2. This is part of the GNU C Intro and Reference Manual
  3. and covered by its license.
  4. @node Preprocessing
  5. @chapter Preprocessing
  6. @c man begin DESCRIPTION
  7. @cindex preprocessing
  8. As the first stage of compiling a C source module, GCC transforms the
  9. text with text substitutions and file inclusions. This is called
  10. @dfn{preprocessing}.
  11. @menu
  12. * Preproc Overview::
  13. * Directives::
  14. * Preprocessing Tokens::
  15. * Header Files::
  16. * Macros::
  17. * Conditionals::
  18. * Diagnostics::
  19. * Line Control::
  20. * Null Directive::
  21. @end menu
  22. @node Preproc Overview
  23. @section Preprocessing Overview
  24. GNU C performs preprocessing on each line of a C program as the first
  25. stage of compilation. Preprocessing operates on a line only when it
  26. contains a @dfn{preprocessing directive} or uses a @dfn{macro}---all
  27. other lines pass through preprocessing unchanged.
  28. Here are some jobs that preprocessing does. The rest of
  29. this chapter gives the details.
  30. @itemize @bullet
  31. @item
  32. Inclusion of header files. These are files (usually containing
  33. declarations and macro definitions) that can be substituted into your
  34. program.
  35. @item
  36. Macro expansion. You can define @dfn{macros}, which are abbreviations
  37. for arbitrary fragments of C code. Preprocessing replaces the macros
  38. with their definitions. Some macros are automatically predefined.
  39. @item
  40. Conditional compilation. You can include or exclude parts of the
  41. program according to various conditions.
  42. @item
  43. Line control. If you use a program to combine or rearrange source files
  44. into an intermediate file that is then compiled, you can use line
  45. control to inform the compiler where each source line originally came
  46. from.
  47. @item
  48. Compilation control. @code{#pragma} and @code{_Pragma} invoke
  49. some special compiler features in how to handle certain constructs.
  50. @item
  51. Diagnostics. You can detect problems at compile time and issue errors
  52. or warnings.
  53. @end itemize
  54. Except for expansion of predefined macros, all these operations happen
  55. only if you use preprocessing directives to request them.
  56. @node Directives
  57. @section Directives
  58. @cindex directives
  59. @cindex preprocessing directives
  60. @cindex directive line
  61. @cindex directive name
  62. @dfn{Preprocessing directives} are lines in the program that start
  63. with @samp{#}. Whitespace is allowed before and after the @samp{#}.
  64. The @samp{#} is followed by an identifier, the @dfn{directive name}.
  65. It specifies the operation to perform. Here are a couple of examples:
  66. @example
  67. #define LIMIT 51
  68. # undef LIMIT
  69. # error You screwed up!
  70. @end example
  71. We usually refer to a directive as @code{#@var{name}} where @var{name}
  72. is the directive name. For example, @code{#define} means the
  73. directive that defines a macro.
  74. The @samp{#} that begins a directive cannot come from a macro
  75. expansion. Also, the directive name is not macro expanded. Thus, if
  76. @code{foo} is defined as a macro expanding to @code{define}, that does
  77. not make @code{#foo} a valid preprocessing directive.
  78. The set of valid directive names is fixed. Programs cannot define new
  79. preprocessing directives.
  80. Some directives require arguments; these make up the rest of the
  81. directive line and must be separated from the directive name by
  82. whitespace. For example, @code{#define} must be followed by a macro
  83. name and the intended expansion of the macro.
  84. A preprocessing directive cannot cover more than one line. The line
  85. can, however, be continued with backslash-newline, or by a
  86. @samp{/*@r{@dots{}}*/}-style comment that extends past the end of the
  87. line. These will be replaced (by nothing, or by whitespace) before
  88. the directive is processed.
  89. @node Preprocessing Tokens
  90. @section Preprocessing Tokens
  91. @cindex preprocessing tokens
  92. Preprocessing divides C code (minus its comments) into
  93. @dfn{tokens} that are similar to C tokens, but not exactly the same.
  94. Here are the quirks of preprocessing tokens.
  95. The main classes of preprocessing tokens are identifiers,
  96. preprocessing numbers, string constants, character constants, and
  97. punctuators; there are a few others too.
  98. @table @asis
  99. @item identifier
  100. @cindex identifiers
  101. An @dfn{identifier} preprocessing token is syntactically like an
  102. identifier in C: any sequence of letters, digits, or underscores, as
  103. well as non-ASCII characters represented using @samp{\U} or @samp{\u},
  104. that doesn't begin with a digit.
  105. During preprocessing, the keywords of C have no special significance;
  106. at that stage, they are simply identifiers. Thus, you can define a
  107. macro whose name is a keyword. The only identifier that is special
  108. during preprocessing is @code{defined} (@pxref{defined}).
  109. @item preprocessing number
  110. @cindex numbers, preprocessing
  111. @cindex preprocessing numbers
  112. A @dfn{preprocessing number} is something that preprocessing treats
  113. textually as a number, including C numeric constants, and other
  114. sequences of characters which resemble numeric constants.
  115. Preprocessing does not try to verify that a preprocessing number is a
  116. valid number in C, and indeed it need not be one.
  117. More precisely, preprocessing numbers begin with an optional period, a
  118. required decimal digit, and then continue with any sequence of
  119. letters, digits, underscores, periods, and exponents. Exponents are
  120. the two-character sequences @samp{e+}, @samp{e-}, @samp{E+},
  121. @samp{E-}, @samp{p+}, @samp{p-}, @samp{P+}, and @samp{P-}. (The
  122. exponents that begin with @samp{p} or @samp{P} are new to C99. They
  123. are used for hexadecimal floating-point constants.)
  124. The reason behind this unusual syntactic class is that the full
  125. complexity of numeric constants is irrelevant during preprocessing.
  126. The distinction between lexically valid and invalid floating-point
  127. numbers, for example, doesn't matter at this stage. The use of
  128. preprocessing numbers makes it possible to split an identifier at any
  129. position and get exactly two tokens, and reliably paste them together
  130. using the @code{##} operator (@pxref{Concatenation}).
  131. @item punctuator
  132. A @dfn{punctuator} is syntactically like an operator.
  133. These are the valid punctuators:
  134. @example
  135. [ ] ( ) @{ @} . ->
  136. ++ -- & * + - ~ !
  137. / % << >> < > <= >= == != ^ | && ||
  138. ? : ; ...
  139. = *= /= %= += -= <<= >>= &= ^= |=
  140. , # ##
  141. <: :> <% %> %: %:%:
  142. @end example
  143. @item string constant
  144. A string constant in the source code is recognized by preprocessing as
  145. a single preprocessing token.
  146. @item character constant
  147. A character constant in the source code is recognized by preprocessing
  148. as a single preprocessing token.
  149. @item header name
  150. Within the @code{#include} directive, preprocessing recognizes a
  151. @dfn{header name} token. It consists of @samp{"@var{name}"}, where
  152. @var{name} is a sequence of source characters other than newline and
  153. @samp{"}, or @samp{<@var{name}>}, where @var{name} is a sequence of
  154. source characters other than newline and @samp{>}.
  155. In practice, it is more convenient to think that the @code{#include} line
  156. is exempt from tokenization.
  157. @item other
  158. Any other character that's valid in a C source program
  159. is treated as a separate preprocessing token.
  160. @end table
  161. Once the program is broken into preprocessing tokens, they remain
  162. separate until the end of preprocessing. Macros that generate two
  163. consecutive tokens insert whitespace to keep them separate, if
  164. necessary. For example,
  165. @example
  166. @group
  167. #define foo() bar
  168. foo()baz
  169. @expansion{} bar baz
  170. @emph{not}
  171. @expansion{} barbaz
  172. @end group
  173. @end example
  174. The only exception is with the @code{##} preprocessing operator, which
  175. pastes tokens together (@pxref{Concatenation}).
  176. Preprocessing treats the null character (code 0) as whitespace, but
  177. generates a warning for it because it may be invisible to the user
  178. (many terminals do not display it at all) and its presence in the file
  179. is probably a mistake.
  180. @node Header Files
  181. @section Header Files
  182. @cindex header file
  183. A header file is a file of C code, typically containing C declarations
  184. and macro definitions (@pxref{Macros}), to be shared between several
  185. source files. You request the use of a header file in your program by
  186. @dfn{including} it, with the C preprocessing directive
  187. @code{#include}.
  188. Header files serve two purposes.
  189. @itemize @bullet
  190. @item
  191. @cindex system header files
  192. System header files declare the interfaces to parts of the operating
  193. system. You include them in your program to supply the definitions and
  194. declarations that you need to invoke system calls and libraries.
  195. @item
  196. Program-specific header files contain declarations for interfaces between the
  197. source files of a particular program. It is a good idea to create a header
  198. file for related declarations and macro definitions if all or most of them
  199. are needed in several different source files.
  200. @end itemize
  201. Including a header file produces the same results as copying the header
  202. file into each source file that needs it. Such copying would be
  203. time-consuming and error-prone. With a header file, the related
  204. declarations appear in only one place. If they need to be changed, you
  205. can change them in one place, and programs that include the header file
  206. will then automatically use the new version when next recompiled. The header
  207. file eliminates the labor of finding and changing all the copies as well
  208. as the risk that a failure to change one copy will result in
  209. inconsistencies within a program.
  210. In C, the usual convention is to give header files names that end with
  211. @file{.h}. It is most portable to use only letters, digits, dashes, and
  212. underscores in header file names, and at most one dot.
  213. The operation of including another source file isn't actually limited
  214. to the sort of code we put into header files. You can put any sort of
  215. C code into a separate file, then use @code{#include} to copy it
  216. virtually into other C source files. But that is a strange thing to
  217. do.
  218. @menu
  219. * include Syntax::
  220. * include Operation::
  221. * Search Path::
  222. * Once-Only Headers::
  223. @c * Alternatives to Wrapper #ifndef::
  224. * Computed Includes::
  225. @c * Wrapper Headers::
  226. @c * System Headers::
  227. @end menu
  228. @node include Syntax
  229. @subsection @code{#include} Syntax
  230. @findex #include
  231. You can specify inclusion of user and system header files with the
  232. preprocessing directive @code{#include}. It has two variants:
  233. @table @code
  234. @item #include <@var{file}>
  235. This variant is used for system header files. It searches for a file
  236. named @var{file} in a standard list of system directories. You can
  237. prepend directories to this list with the @option{-I} option
  238. (@pxref{Invocation, Invoking GCC, Invoking GCC, gcc, Using the GNU
  239. Compiler Collection}).
  240. @item #include "@var{file}"
  241. This variant is used for header files of your own program. It
  242. searches for a file named @var{file} first in the directory containing
  243. the current file, then in the quote directories, then the same
  244. directories used for @code{<@var{file}>}. You can prepend directories
  245. to the list of quote directories with the @option{-iquote} option.
  246. @end table
  247. The argument of @code{#include}, whether delimited with quote marks or
  248. angle brackets, behaves like a string constant in that comments are not
  249. recognized, and macro names are not expanded. Thus, @code{@w{#include
  250. <x/*y>}} specifies inclusion of a system header file named @file{x/*y}.
  251. However, if backslashes occur within @var{file}, they are considered
  252. ordinary text characters, not escape characters: character escape
  253. sequences such as used in string constants in C are not meaningful
  254. here. Thus, @code{@w{#include "x\n\\y"}} specifies a filename
  255. containing three backslashes. By the same token, there is no way to
  256. escape @samp{"} or @samp{>} to include it in the header file name if
  257. it would instead end the file name.
  258. Some systems interpret @samp{\} as a file name component separator.
  259. All these systems also interpret @samp{/} the same way. It is most
  260. portable to use only @samp{/}.
  261. It is an error to put anything other than comments on the
  262. @code{#include} line after the file name.
  263. @node include Operation
  264. @subsection @code{#include} Operation
  265. The @code{#include} directive works by scanning the specified header
  266. file as input before continuing with the rest of the current file.
  267. The result of preprocessing consists of the text already generated,
  268. followed by the result of preprocessing the included file, followed by
  269. whatever results from the text after the @code{#include} directive.
  270. For example, if you have a header file @file{header.h} as follows,
  271. @example
  272. char *test (void);
  273. @end example
  274. @noindent
  275. and a main program called @file{program.c} that uses the header file,
  276. like this,
  277. @example
  278. int x;
  279. #include "header.h"
  280. int
  281. main (void)
  282. @{
  283. puts (test ());
  284. @}
  285. @end example
  286. @noindent
  287. the result is equivalent to putting this text in @file{program.c}:
  288. @example
  289. int x;
  290. char *test (void);
  291. int
  292. main (void)
  293. @{
  294. puts (test ());
  295. @}
  296. @end example
  297. Included files are not limited to declarations and macro definitions;
  298. those are merely the typical uses. Any fragment of a C program can be
  299. included from another file. The include file could even contain the
  300. beginning of a statement that is concluded in the containing file, or
  301. the end of a statement that was started in the including file. However,
  302. an included file must consist of complete tokens. Comments and string
  303. literals that have not been closed by the end of an included file are
  304. invalid. For error recovery, the compiler terminates them at the end of
  305. the file.
  306. To avoid confusion, it is best if header files contain only complete
  307. syntactic units---function declarations or definitions, type
  308. declarations, etc.
  309. The line following the @code{#include} directive is always treated as
  310. a separate line, even if the included file lacks a final newline.
  311. There is no problem putting a preprocessing directive there.
  312. @node Search Path
  313. @subsection Search Path
  314. GCC looks in several different places for header files to be included.
  315. On the GNU system, and Unix systems, the default directories for
  316. system header files are:
  317. @example
  318. @var{libdir}/gcc/@var{target}/@var{version}/include
  319. /usr/local/include
  320. @var{libdir}/gcc/@var{target}/@var{version}/include-fixed
  321. @var{libdir}/@var{target}/include
  322. /usr/include/@var{target}
  323. /usr/include
  324. @end example
  325. @noindent
  326. The list may be different in some operating systems. Other
  327. directories are added for C++.
  328. In the above, @var{target} is the canonical name of the system GCC was
  329. configured to compile code for; often but not always the same as the
  330. canonical name of the system it runs on. @var{version} is the version
  331. of GCC in use.
  332. You can add to this list with the @option{-I@var{dir}} command-line
  333. option. All the directories named by @option{-I} are searched, in
  334. left-to-right order, @emph{before} the default directories. The only
  335. exception is when @file{dir} is already searched by default. In
  336. this case, the option is ignored and the search order for system
  337. directories remains unchanged.
  338. Duplicate directories are removed from the quote and bracket search
  339. chains before the two chains are merged to make the final search chain.
  340. Thus, it is possible for a directory to occur twice in the final search
  341. chain if it was specified in both the quote and bracket chains.
  342. You can prevent GCC from searching any of the default directories with
  343. the @option{-nostdinc} option. This is useful when you are compiling an
  344. operating system kernel or some other program that does not use the
  345. standard C library facilities, or the standard C library itself.
  346. @option{-I} options are not ignored as described above when
  347. @option{-nostdinc} is in effect.
  348. GCC looks for headers requested with @code{@w{#include "@var{file}"}}
  349. first in the directory containing the current file, then in the
  350. @dfn{quote directories} specified by @option{-iquote} options, then in
  351. the same places it looks for a system header. For example, if
  352. @file{/usr/include/sys/stat.h} contains @code{@w{#include "types.h"}},
  353. GCC looks for @file{types.h} first in @file{/usr/include/sys}, then in
  354. the quote directories and then in its usual search path.
  355. @code{#line} (@pxref{Line Control}) does not change GCC's idea of the
  356. directory containing the current file.
  357. @cindex quote directories
  358. The @option{-I-} is an old-fashioned, deprecated way to specify the
  359. quote directories. To look for headers in a directory named @file{-},
  360. specify @option{-I./-}. There are several more ways to adjust the
  361. header search path. @xref{invocation, Invoking GCC, Invoking GCC,
  362. gcc, Using the GNU Compiler Collection}.
  363. @node Once-Only Headers
  364. @subsection Once-Only Headers
  365. @cindex repeated inclusion
  366. @cindex including just once
  367. @cindex wrapper @code{#ifndef}
  368. If a header file happens to be included twice, the compiler will process
  369. its contents twice. This is very likely to cause an error, e.g.@: when the
  370. compiler sees the same structure definition twice.
  371. The standard way to prevent this is to enclose the entire real contents
  372. of the file in a conditional, like this:
  373. @example
  374. @group
  375. /* File foo. */
  376. #ifndef FILE_FOO_SEEN
  377. #define FILE_FOO_SEEN
  378. @var{the entire file}
  379. #endif /* !FILE_FOO_SEEN */
  380. @end group
  381. @end example
  382. This construct is commonly known as a @dfn{wrapper #ifndef}. When the
  383. header is included again, the conditional will be false, because
  384. @code{FILE_FOO_SEEN} is defined. Preprocessing skips over the entire
  385. contents of the file, so that compilation will never ``see'' the file
  386. contents twice in one module.
  387. GCC optimizes this case even further. It remembers when a header file
  388. has a wrapper @code{#ifndef}. If a subsequent @code{#include}
  389. specifies that header, and the macro in the @code{#ifndef} is still
  390. defined, it does not bother to rescan the file at all.
  391. You can put comments in the header file outside the wrapper. They
  392. do not interfere with this optimization.
  393. @cindex controlling macro
  394. @cindex guard macro
  395. The macro @code{FILE_FOO_SEEN} is called the @dfn{controlling macro}
  396. or @dfn{guard macro}. In a user header file, the macro name should
  397. not begin with @samp{_}. In a system header file, it should begin
  398. with @samp{__} (or @samp{_} followed by an upper-case letter) to avoid
  399. conflicts with user programs. In any kind of header file, the macro
  400. name should contain the name of the file and some additional text, to
  401. avoid conflicts with other header files.
  402. @node Computed Includes
  403. @subsection Computed Includes
  404. @cindex computed includes
  405. @cindex macros in include
  406. Sometimes it is necessary to select one of several different header
  407. files to be included into your program. They might specify
  408. configuration parameters to be used on different sorts of operating
  409. systems, for instance. You could do this with a series of conditionals,
  410. @example
  411. #if SYSTEM_1
  412. # include "system_1.h"
  413. #elif SYSTEM_2
  414. # include "system_2.h"
  415. #elif SYSTEM_3
  416. /* @r{@dots{}} */
  417. #endif
  418. @end example
  419. That rapidly becomes tedious. Instead, GNU C offers the ability to use
  420. a macro for the header name. This is called a @dfn{computed include}.
  421. Instead of writing a header name as the direct argument of
  422. @code{#include}, you simply put a macro name there instead:
  423. @example
  424. #define SYSTEM_H "system_1.h"
  425. /* @r{@dots{}} */
  426. #include SYSTEM_H
  427. @end example
  428. @noindent
  429. @code{SYSTEM_H} is expanded, then @file{system_1.h} is included as if
  430. the @code{#include} had been written with that name. @code{SYSTEM_H}
  431. could be defined by your Makefile with a @option{-D} option.
  432. You must be careful when you define such a macro. @code{#define}
  433. saves tokens, not text. GCC has no way of knowing that the macro will
  434. be used as the argument of @code{#include}, so it generates ordinary
  435. tokens, not a header name. This is unlikely to cause problems if you
  436. use double-quote includes, which are syntactically similar to string
  437. constants. If you use angle brackets, however, you may have trouble.
  438. The syntax of a computed include is actually a bit more general than the
  439. above. If the first non-whitespace character after @code{#include} is
  440. not @samp{"} or @samp{<}, then the entire line is macro-expanded
  441. like running text would be.
  442. If the line expands to a single string constant, the contents of that
  443. string constant are the file to be included. Preprocessing does not
  444. re-examine the string for embedded quotes, but neither does it process
  445. backslash escapes in the string. Therefore
  446. @example
  447. #define HEADER "a\"b"
  448. #include HEADER
  449. @end example
  450. @noindent
  451. looks for a file named @file{a\"b}. Preprocessing searches for the
  452. file according to the rules for double-quoted includes.
  453. If the line expands to a token stream beginning with a @samp{<} token
  454. and including a @samp{>} token, then the tokens between the @samp{<} and
  455. the first @samp{>} are combined to form the filename to be included.
  456. Any whitespace between tokens is reduced to a single space; then any
  457. space after the initial @samp{<} is retained, but a trailing space
  458. before the closing @samp{>} is ignored. Preprocessing searches for the file
  459. according to the rules for angle-bracket includes.
  460. In either case, if there are any tokens on the line after the file name,
  461. an error occurs and the directive is not processed. It is also an error
  462. if the result of expansion does not match either of the two expected
  463. forms.
  464. These rules are implementation-defined behavior according to the C
  465. standard. To minimize the risk of different compilers interpreting your
  466. computed includes differently, we recommend you use only a single
  467. object-like macro that expands to a string constant. That also
  468. makes it clear to people reading your program.
  469. @node Macros
  470. @section Macros
  471. @cindex macros
  472. A @dfn{macro} is a fragment of code that has been given a name.
  473. Whenever the name is used, it is replaced by the contents of the macro.
  474. There are two kinds of macros. They differ mostly in what they look
  475. like when they are used. @dfn{Object-like} macros resemble data objects
  476. when used, @dfn{function-like} macros resemble function calls.
  477. You may define any valid identifier as a macro, even if it is a C
  478. keyword. In the preprocessing stage, GCC does not know anything about
  479. keywords. This can be useful if you wish to hide a keyword such as
  480. @code{const} from an older compiler that does not understand it.
  481. However, the preprocessing operator @code{defined} (@pxref{defined})
  482. can never be defined as a macro, and C@code{++}'s named operators
  483. (@pxref{C++ Named Operators, C++ Named Operators, C++ Named Operators,
  484. gcc, Using the GNU Compiler Collection}) cannot be macros when
  485. compiling C@code{++} code.
  486. The operator @code{#} is used in macros for stringification of an
  487. argument (@pxref{Stringification}), and @code{##} is used for
  488. concatenation of arguments into larger tokens (@pxref{Concatenation})
  489. @menu
  490. * Object-like Macros::
  491. * Function-like Macros::
  492. @c * Macro Pragmas::
  493. * Macro Arguments::
  494. * Stringification::
  495. * Concatenation::
  496. * Variadic Macros::
  497. * Predefined Macros::
  498. * Undefining and Redefining Macros::
  499. * Directives Within Macro Arguments::
  500. * Macro Pitfalls::
  501. @end menu
  502. @node Object-like Macros
  503. @subsection Object-like Macros
  504. @cindex object-like macro
  505. @cindex symbolic constants
  506. @cindex manifest constants
  507. An @dfn{object-like macro} is a simple identifier that will be
  508. replaced by a code fragment. It is called object-like because in most
  509. cases the use of the macro looks like reference to a data object in
  510. code that uses it. These macros are most commonly used to give
  511. symbolic names to numeric constants.
  512. @findex #define
  513. The way to define macros with the @code{#define} directive.
  514. @code{#define} is followed by the name of the macro and then the token
  515. sequence it should be an abbreviation for, which is variously referred
  516. to as the macro's @dfn{body}, @dfn{expansion} or @dfn{replacement
  517. list}. For example,
  518. @example
  519. #define BUFFER_SIZE 1024
  520. @end example
  521. @noindent
  522. defines a macro named @code{BUFFER_SIZE} as an abbreviation for the
  523. token @code{1024}. If somewhere after this @code{#define} directive
  524. there comes a C statement of the form
  525. @example
  526. foo = (char *) malloc (BUFFER_SIZE);
  527. @end example
  528. @noindent
  529. then preprocessing will recognize and @dfn{expand} the macro
  530. @code{BUFFER_SIZE}, so that compilation will see the tokens:
  531. @example
  532. foo = (char *) malloc (1024);
  533. @end example
  534. By convention, macro names are written in upper case. Programs are
  535. easier to read when it is possible to tell at a glance which names are
  536. macros. Macro names that start with @samp{__} are reserved for
  537. internal uses, and many of them are defined automatically, so don't
  538. define such macro names unless you really know what you're doing.
  539. Likewise for macro names that start with @samp{_} and an upper-case letter.
  540. The macro's body ends at the end of the @code{#define} line. You may
  541. continue the definition onto multiple lines, if necessary, using
  542. backslash-newline. When the macro is expanded, however, it will all
  543. come out on one line. For example,
  544. @example
  545. #define NUMBERS 1, \
  546. 2, \
  547. 3
  548. int x[] = @{ NUMBERS @};
  549. @expansion{} int x[] = @{ 1, 2, 3 @};
  550. @end example
  551. @noindent
  552. The most common visible consequence of this is surprising line numbers
  553. in error messages.
  554. There is no restriction on what can go in a macro body provided it
  555. decomposes into valid preprocessing tokens. Parentheses need not
  556. balance, and the body need not resemble valid C code. (If it does not,
  557. you may get error messages from the C compiler when you use the macro.)
  558. Preprocessing scans the program sequentially. A macro definition
  559. takes effect right after its appearance. Therefore, the following
  560. input
  561. @example
  562. foo = X;
  563. #define X 4
  564. bar = X;
  565. @end example
  566. @noindent
  567. produces
  568. @example
  569. foo = X;
  570. bar = 4;
  571. @end example
  572. When preprocessing expands a macro name, the macro's expansion
  573. replaces the macro invocation, then the expansion is examined for more
  574. macros to expand. For example,
  575. @example
  576. @group
  577. #define TABLESIZE BUFSIZE
  578. #define BUFSIZE 1024
  579. TABLESIZE
  580. @expansion{} BUFSIZE
  581. @expansion{} 1024
  582. @end group
  583. @end example
  584. @noindent
  585. @code{TABLESIZE} is expanded first to produce @code{BUFSIZE}, then that
  586. macro is expanded to produce the final result, @code{1024}.
  587. Notice that @code{BUFSIZE} was not defined when @code{TABLESIZE} was
  588. defined. The @code{#define} for @code{TABLESIZE} uses exactly the
  589. expansion you specify---in this case, @code{BUFSIZE}---and does not
  590. check to see whether it too contains macro names. Only when you
  591. @emph{use} @code{TABLESIZE} is the result of its expansion scanned for
  592. more macro names.
  593. This makes a difference if you change the definition of @code{BUFSIZE}
  594. at some point in the source file. @code{TABLESIZE}, defined as shown,
  595. will always expand using the definition of @code{BUFSIZE} that is
  596. currently in effect:
  597. @example
  598. #define BUFSIZE 1020
  599. #define TABLESIZE BUFSIZE
  600. #undef BUFSIZE
  601. #define BUFSIZE 37
  602. @end example
  603. @noindent
  604. Now @code{TABLESIZE} expands (in two stages) to @code{37}.
  605. If the expansion of a macro contains its own name, either directly or
  606. via intermediate macros, it is not expanded again when the expansion is
  607. examined for more macros. This prevents infinite recursion.
  608. @xref{Self-Referential Macros}, for the precise details.
  609. @node Function-like Macros
  610. @subsection Function-like Macros
  611. @cindex function-like macros
  612. You can also define macros whose use looks like a function call.
  613. These are called @dfn{function-like macros}. To define one, use the
  614. @code{#define} directive with a pair of parentheses immediately after
  615. the macro name. For example,
  616. @example
  617. #define lang_init() c_init ()
  618. lang_init ()
  619. @expansion{} c_init ()
  620. lang_init ()
  621. @expansion{} c_init ()
  622. lang_init()
  623. @expansion{} c_init ()
  624. @end example
  625. There must be no space between the macro name and the following
  626. open-parenthesis in the the @code{#define} directive; that's what
  627. indicates you're defining a function-like macro. However, you can add
  628. unnecessary whitespace around the open-parenthesis (and around the
  629. close-parenthesis) when you @emph{call} the macro; they don't change
  630. anything.
  631. A function-like macro is expanded only when its name appears with a
  632. pair of parentheses after it. If you write just the name, without
  633. parentheses, it is left alone. This can be useful when you have a
  634. function and a macro of the same name, and you wish to use the
  635. function sometimes. Whitespace and line breaks before or between the
  636. parentheses are ignored when the macro is called.
  637. @example
  638. extern void foo(void);
  639. #define foo() /* @r{optimized inline version} */
  640. /* @r{@dots{}} */
  641. foo();
  642. funcptr = foo;
  643. @end example
  644. Here the call to @code{foo()} expands the macro, but the function
  645. pointer @code{funcptr} gets the address of the real function
  646. @code{foo}. If the macro were to be expanded there, it would cause a
  647. syntax error.
  648. If you put spaces between the macro name and the parentheses in the
  649. macro definition, that does not define a function-like macro, it defines
  650. an object-like macro whose expansion happens to begin with a pair of
  651. parentheses. Here is an example:
  652. @example
  653. #define lang_init () c_init()
  654. lang_init()
  655. @expansion{} () c_init()()
  656. @end example
  657. The first two pairs of parentheses in this expansion come from the
  658. macro. The third is the pair that was originally after the macro
  659. invocation. Since @code{lang_init} is an object-like macro, it does not
  660. consume those parentheses.
  661. Any name can have at most one macro definition at a time. Thus,
  662. you can't define the same name as an object-like macro and a
  663. function-like macro at once.
  664. @node Macro Arguments
  665. @subsection Macro Arguments
  666. @cindex arguments
  667. @cindex macros with arguments
  668. @cindex arguments in macro definitions
  669. Function-like macros can take @dfn{arguments}, just like true functions.
  670. To define a macro that uses arguments, you insert @dfn{parameters}
  671. between the pair of parentheses in the macro definition that make the
  672. macro function-like. The parameters must be valid C identifiers,
  673. separated by commas and optionally whitespace.
  674. To invoke a macro that takes arguments, you write the name of the macro
  675. followed by a list of @dfn{actual arguments} in parentheses, separated
  676. by commas. The invocation of the macro need not be restricted to a
  677. single logical line---it can cross as many lines in the source file as
  678. you wish. The number of arguments you give must match the number of
  679. parameters in the macro definition. When the macro is expanded, each
  680. use of a parameter in its body is replaced by the tokens of the
  681. corresponding argument. (The macro body is not required to use all of the
  682. parameters.)
  683. As an example, here is a macro that computes the minimum of two numeric
  684. values, as it is defined in many C programs, and some uses.
  685. @example
  686. #define min(X, Y) ((X) < (Y) ? (X) : (Y))
  687. x = min(a, b); @expansion{} x = ((a) < (b) ? (a) : (b));
  688. y = min(1, 2); @expansion{} y = ((1) < (2) ? (1) : (2));
  689. z = min(a+28, *p); @expansion{} z = ((a+28) < (*p) ? (a+28) : (*p));
  690. @end example
  691. @noindent
  692. In this small example you can already see several of the dangers of
  693. macro arguments. @xref{Macro Pitfalls}, for detailed explanations.
  694. Leading and trailing whitespace in each argument is dropped, and all
  695. whitespace between the tokens of an argument is reduced to a single
  696. space. Parentheses within each argument must balance; a comma within
  697. such parentheses does not end the argument. However, there is no
  698. requirement for square brackets or braces to balance, and they do not
  699. prevent a comma from separating arguments. Thus,
  700. @example
  701. macro (array[x = y, x + 1])
  702. @end example
  703. @noindent
  704. passes two arguments to @code{macro}: @code{array[x = y} and @code{x +
  705. 1]}. If you want to supply @code{array[x = y, x + 1]} as an argument,
  706. you can write it as @code{array[(x = y, x + 1)]}, which is equivalent C
  707. code. However, putting an assignment inside an array subscript
  708. is to be avoided anyway.
  709. All arguments to a macro are completely macro-expanded before they are
  710. substituted into the macro body. After substitution, the complete text
  711. is scanned again for macros to expand, including the arguments. This rule
  712. may seem strange, but it is carefully designed so you need not worry
  713. about whether any function call is actually a macro invocation. You can
  714. run into trouble if you try to be too clever, though. @xref{Argument
  715. Prescan}, for detailed discussion.
  716. For example, @code{min (min (a, b), c)} is first expanded to
  717. @example
  718. min (((a) < (b) ? (a) : (b)), (c))
  719. @end example
  720. @noindent
  721. and then to
  722. @example
  723. @group
  724. ((((a) < (b) ? (a) : (b))) < (c)
  725. ? (((a) < (b) ? (a) : (b)))
  726. : (c))
  727. @end group
  728. @end example
  729. @noindent
  730. (The line breaks shown here for clarity are not actually generated.)
  731. @cindex empty macro arguments
  732. You can leave macro arguments empty without error, but many macros
  733. will then expand to invalid code. You cannot leave out arguments
  734. entirely; if a macro takes two arguments, there must be exactly one
  735. comma at the top level of its argument list. Here are some silly
  736. examples using @code{min}:
  737. @smallexample
  738. min(, b) @expansion{} (( ) < (b) ? ( ) : (b))
  739. min(a, ) @expansion{} ((a ) < ( ) ? (a ) : ( ))
  740. min(,) @expansion{} (( ) < ( ) ? ( ) : ( ))
  741. min((,),) @expansion{} (((,)) < ( ) ? ((,)) : ( ))
  742. min() @error{} macro "min" requires 2 arguments, but only 1 given
  743. min(,,) @error{} macro "min" passed 3 arguments, but takes just 2
  744. @end smallexample
  745. Whitespace is not a preprocessing token, so if a macro @code{foo} takes
  746. one argument, @code{@w{foo ()}} and @code{@w{foo ( )}} both supply it an
  747. empty argument.
  748. @ignore @c How long ago was this?
  749. Previous GNU preprocessor implementations and
  750. documentation were incorrect on this point, insisting that a
  751. function-like macro that takes a single argument be passed a space if an
  752. empty argument was required.
  753. @end ignore
  754. Macro parameters appearing inside string literals are not replaced by
  755. their corresponding actual arguments.
  756. @example
  757. #define foo(x) x, "x"
  758. foo(bar) @expansion{} bar, "x"
  759. @end example
  760. @noindent
  761. See the next subsection for how to insert macro arguments
  762. into a string literal.
  763. The token following the macro call and the last token of the macro
  764. expansion do not become one token even if it looks like they could:
  765. @example
  766. #define foo() abc
  767. foo()def @expansion{} abc def
  768. @end example
  769. @node Stringification
  770. @subsection Stringification
  771. @cindex stringification
  772. @cindex @code{#} operator
  773. Sometimes you may want to convert a macro argument into a string
  774. constant. Parameters are not replaced inside string constants, but
  775. you can use the @code{#} preprocessing operator instead. When a macro
  776. parameter is used with a leading @code{#}, preprocessing replaces it
  777. with the literal text of the actual argument, converted to a string
  778. constant. Unlike normal parameter replacement, the argument is not
  779. macro-expanded first. This is called @dfn{stringification}.
  780. There is no way to combine an argument with surrounding text and
  781. stringify it all together. But you can write a series of string
  782. constants and stringified arguments. After preprocessing replaces the
  783. stringified arguments with string constants, the consecutive string
  784. constants will be concatenated into one long string constant
  785. (@pxref{String Constants}).
  786. Here is an example that uses stringification and concatenation of
  787. string constants:
  788. @example
  789. @group
  790. #define WARN_IF(EXP) \
  791. do @{ if (EXP) \
  792. fprintf (stderr, "Warning: " #EXP "\n"); @} \
  793. while (0)
  794. WARN_IF (x == 0);
  795. @expansion{}
  796. do @{ if (x == 0)
  797. fprintf (stderr, "Warning: " "x == 0" "\n"); @}
  798. while (0);
  799. @end group
  800. @end example
  801. @noindent
  802. The argument for @code{EXP} is substituted once, as is, into the
  803. @code{if} statement, and once, stringified, into the argument to
  804. @code{fprintf}. If @code{x} were a macro, it would be expanded in the
  805. @code{if} statement but not in the string.
  806. The @code{do} and @code{while (0)} are a kludge to make it possible to
  807. write @code{WARN_IF (@var{arg});}. The resemblance of @code{WARN_IF}
  808. to a function makes that a natural way to write it.
  809. @xref{Swallowing the Semicolon}.
  810. Stringification in C involves more than putting double-quote
  811. characters around the fragment. It also backslash-escapes the quotes
  812. surrounding embedded string constants, and all backslashes within
  813. string and character constants, in order to get a valid C string
  814. constant with the proper contents. Thus, stringifying @code{@w{p =
  815. "foo\n";}} results in @t{@w{"p = \"foo\\n\";"}}. However, backslashes
  816. that are not inside string or character constants are not duplicated:
  817. @samp{\n} by itself stringifies to @t{"\n"}.
  818. All leading and trailing whitespace in text being stringified is
  819. ignored. Any sequence of whitespace in the middle of the text is
  820. converted to a single space in the stringified result. Comments are
  821. replaced by whitespace long before stringification happens, so they
  822. never appear in stringified text.
  823. There is no way to convert a macro argument into a character constant.
  824. To stringify the result of expansion of a macro argument, you have to
  825. use two levels of macros, like this:
  826. @example
  827. #define xstr(S) str(S)
  828. #define str(s) #s
  829. #define foo 4
  830. str (foo)
  831. @expansion{} "foo"
  832. xstr (foo)
  833. @expansion{} xstr (4)
  834. @expansion{} str (4)
  835. @expansion{} "4"
  836. @end example
  837. @code{s} is stringified when it is used in @code{str}, so it is not
  838. macro-expanded first. But @code{S} is an ordinary argument to
  839. @code{xstr}, so it is completely macro-expanded before @code{xstr}
  840. itself is expanded (@pxref{Argument Prescan}). Therefore, by the time
  841. @code{str} gets to its argument text, that text already been
  842. macro-expanded.
  843. @node Concatenation
  844. @subsection Concatenation
  845. @cindex concatenation
  846. @cindex token pasting
  847. @cindex token concatenation
  848. @cindex @code{##} operator
  849. It is often useful to merge two tokens into one while expanding macros.
  850. This is called @dfn{token pasting} or @dfn{token concatenation}. The
  851. @code{##} preprocessing operator performs token pasting. When a macro
  852. is expanded, the two tokens on either side of each @code{##} operator
  853. are combined into a single token, which then replaces the @code{##} and
  854. the two original tokens in the macro expansion. Usually both will be
  855. identifiers, or one will be an identifier and the other a preprocessing
  856. number. When pasted, they make a longer identifier.
  857. Concatenation into an identifier isn't the only valid case. It is
  858. also possible to concatenate two numbers (or a number and a name, such
  859. as @code{1.5} and @code{e3}) into a number. Also, multi-character
  860. operators such as @code{+=} can be formed by token pasting.
  861. However, two tokens that don't together form a valid token cannot be
  862. pasted together. For example, you cannot concatenate @code{x} with
  863. @code{+}, not in either order. Trying this issues a warning and keeps
  864. the two tokens separate. Whether it puts white space between the
  865. tokens is undefined. It is common to find unnecessary uses of
  866. @code{##} in complex macros. If you get this warning, it is likely
  867. that you can simply remove the @code{##}.
  868. The tokens combined by @code{##} could both come from the macro body,
  869. but then you could just as well write them as one token in the first place.
  870. Token pasting is useful when one or both of the tokens comes from a
  871. macro argument. If either of the tokens next to an @code{##} is a
  872. parameter name, it is replaced by its actual argument before @code{##}
  873. executes. As with stringification, the actual argument is not
  874. macro-expanded first. If the argument is empty, that @code{##} has no
  875. effect.
  876. Keep in mind that preprocessing converts comments to whitespace before
  877. it looks for uses of macros. Therefore, you cannot create a comment
  878. by concatenating @samp{/} and @samp{*}. You can put as much
  879. whitespace between @code{##} and its operands as you like, including
  880. comments, and you can put comments in arguments that will be
  881. concatenated.
  882. It is an error to use @code{##} at the beginning or end of a macro
  883. body.
  884. Multiple @code{##} operators are handled left-to-right, so that
  885. @samp{1 ## e ## -2} pastes into @samp{1e-2}. (Right-to-left
  886. processing would first generate @samp{e-2}, which is an invalid token.)
  887. When @code{#} and @code{##} are used together, they are all handled
  888. left-to-right.
  889. Consider a C program that interprets named commands. There probably
  890. needs to be a table of commands, perhaps an array of structures declared
  891. as follows:
  892. @example
  893. @group
  894. struct command
  895. @{
  896. char *name;
  897. void (*function) (void);
  898. @};
  899. @end group
  900. @group
  901. struct command commands[] =
  902. @{
  903. @{ "quit", quit_command @},
  904. @{ "help", help_command @},
  905. /* @r{@dots{}} */
  906. @};
  907. @end group
  908. @end example
  909. It would be cleaner not to have to write each command name twice, once
  910. in the string constant and once in the function name. A macro that
  911. takes the name of a command as an argument can make this unnecessary.
  912. It can create the string constant with stringification, and the
  913. function name by concatenating the argument with @samp{_command}.
  914. Here is how it is done:
  915. @example
  916. #define COMMAND(NAME) @{ #NAME, NAME ## _command @}
  917. struct command commands[] =
  918. @{
  919. COMMAND (quit),
  920. COMMAND (help),
  921. /* @r{@dots{}} */
  922. @};
  923. @end example
  924. @node Variadic Macros
  925. @subsection Variadic Macros
  926. @cindex variable number of arguments
  927. @cindex macros with variable arguments
  928. @cindex variadic macros
  929. A macro can be declared to accept a variable number of arguments much as
  930. a function can. The syntax for defining the macro is similar to that of
  931. a function. Here is an example:
  932. @example
  933. #define eprintf(@dots{}) fprintf (stderr, __VA_ARGS__)
  934. @end example
  935. This kind of macro is called @dfn{variadic}. When the macro is invoked,
  936. all the tokens in its argument list after the last named argument (this
  937. macro has none), including any commas, become the @dfn{variable
  938. argument}. This sequence of tokens replaces the identifier
  939. @code{@w{__VA_ARGS__}} in the macro body wherever it appears. Thus, we
  940. have this expansion:
  941. @example
  942. eprintf ("%s:%d: ", input_file, lineno)
  943. @expansion{} fprintf (stderr, "%s:%d: ", input_file, lineno)
  944. @end example
  945. The variable argument is completely macro-expanded before it is inserted
  946. into the macro expansion, just like an ordinary argument. You may use
  947. the @code{#} and @code{##} operators to stringify the variable argument
  948. or to paste its leading or trailing token with another token. (But see
  949. below for an important special case for @code{##}.)
  950. @strong{Warning:} don't use the identifier @code{@w{__VA_ARGS__}}
  951. for anything other than this.
  952. If your macro is complicated, you may want a more descriptive name for
  953. the variable argument than @code{@w{__VA_ARGS__}}. You can write an
  954. argument name immediately before the @samp{@dots{}}; that name is used
  955. for the variable argument.@footnote{GNU C extension.} The
  956. @code{eprintf} macro above could be written thus:
  957. @example
  958. #define eprintf(args@dots{}) fprintf (stderr, args)
  959. @end example
  960. A variadic macro can have named arguments as well as variable
  961. arguments, so @code{eprintf} can be defined like this, instead:
  962. @example
  963. #define eprintf(format, @dots{}) \
  964. fprintf (stderr, format, __VA_ARGS__)
  965. @end example
  966. @noindent
  967. This formulation is more descriptive, but what if you want to specify
  968. a format string that takes no arguments? In GNU C, you can omit the
  969. comma before the variable arguments if they are empty, but that puts
  970. an extra comma in the expansion:
  971. @example
  972. eprintf ("success!\n")
  973. @expansion{} fprintf(stderr, "success!\n", )
  974. @end example
  975. @noindent
  976. That's an error in the call to @code{fprintf}.
  977. To get rid of that comma, the @code{##} token paste operator has a
  978. special meaning when placed between a comma and a variable
  979. argument.@footnote{GNU C extension.} If you write
  980. @example
  981. #define eprintf(format, @dots{}) \
  982. fprintf (stderr, format, ##__VA_ARGS__)
  983. @end example
  984. @noindent
  985. then use the macro @code{eprintf} with empty variable arguments,
  986. @code{##} deletes the preceding comma.
  987. @example
  988. eprintf ("success!\n")
  989. @expansion{} fprintf(stderr, "success!\n")
  990. @end example
  991. @noindent
  992. This does @emph{not} happen if you pass an empty argument, nor does it
  993. happen if the token preceding @code{##} is anything other than a
  994. comma.
  995. @noindent
  996. When the only macro parameter is a variable arguments parameter, and
  997. the macro call has no argument at all, it is not obvious whether that
  998. means an empty argument or a missing argument. Should the comma be
  999. kept, or deleted? The C standard says to keep the comma, but the
  1000. preexisting GNU C extension deleted the comma. Nowadays, GNU C
  1001. retains the comma when implementing a specific C standard, and deletes
  1002. it otherwise.
  1003. C99 mandates that the only place the identifier @code{@w{__VA_ARGS__}}
  1004. can appear is in the replacement list of a variadic macro. It may not
  1005. be used as a macro name, macro parameter name, or within a different
  1006. type of macro. It may also be forbidden in open text; the standard is
  1007. ambiguous. We recommend you avoid using that name except for its
  1008. special purpose.
  1009. Variadic macros where you specify the parameter name is a GNU C
  1010. feature that has been supported for a long time. Standard C, as of
  1011. C99, supports only the form where the parameter is called
  1012. @code{@w{__VA_ARGS__}}. For portability to previous versions of GNU C
  1013. you should use only named variable argument parameters. On the other
  1014. hand, for portability to other C99 compilers, you should use only
  1015. @code{@w{__VA_ARGS__}}.
  1016. @node Predefined Macros
  1017. @subsection Predefined Macros
  1018. @cindex predefined macros
  1019. Several object-like macros are predefined; you use them without
  1020. supplying their definitions. Here we explain the ones user programs
  1021. often need to use. Many other macro names starting with @samp{__} are
  1022. predefined; in general, you should not define such macro names
  1023. yourself.
  1024. @table @code
  1025. @item __FILE__
  1026. This macro expands to the name of the current input file, in the form
  1027. of a C string constant. This is the full name by which the GCC opened
  1028. the file, not the short name specified in @code{#include} or as the
  1029. input file name argument. For example,
  1030. @code{"/usr/local/include/myheader.h"} is a possible expansion of this
  1031. macro.
  1032. @item __LINE__
  1033. This macro expands to the current input line number, in the form of a
  1034. decimal integer constant. While we call it a predefined macro, it's
  1035. a pretty strange macro, since its ``definition'' changes with each
  1036. new line of source code.
  1037. @item __func__
  1038. @itemx __FUNCTION__
  1039. These names are like variables that have as value a string containing
  1040. the name of the current function definition. They are not really
  1041. macros, but this is the best place to mention them.
  1042. @code{__FUNCTION__} is the name that has been defined in GNU C since
  1043. time immemorial; @code{__func__} is defined by the C standard.
  1044. With the following conditionals, you can use whichever one is defined.
  1045. @example
  1046. #if __STDC_VERSION__ < 199901L
  1047. # if __GNUC__ >= 2
  1048. # define __func__ __FUNCTION__
  1049. # else
  1050. # define __func__ "<unknown>"
  1051. # endif
  1052. #endif
  1053. @end example
  1054. @item __PRETTY_FUNCTION__
  1055. This is equivalent to @code{__FUNCTION__} in C, but in C@code{++}
  1056. the string includes argument type information as well.
  1057. It is a GNU C extension.
  1058. @end table
  1059. Those features are useful in generating an error message to report an
  1060. inconsistency detected by the program; the message can state the
  1061. source line where the inconsistency was detected. For example,
  1062. @example
  1063. fprintf (stderr, "Internal error: "
  1064. "negative string length "
  1065. "in function %s "
  1066. "%d at %s, line %d.",
  1067. __func__, length, __FILE__, __LINE__);
  1068. @end example
  1069. A @code{#line} directive changes @code{__LINE__}, and may change
  1070. @code{__FILE__} as well. @xref{Line Control}.
  1071. @table @code
  1072. @item __DATE__
  1073. This macro expands to a string constant that describes the date of
  1074. compilation. The string constant contains eleven characters and looks
  1075. like @code{@w{"Feb 12 1996"}}. If the day of the month is just one
  1076. digit, an extra space precedes it so that the date is always eleven
  1077. characters.
  1078. If the compiler cannot determine the current date, it emits a warning messages
  1079. (once per compilation) and @code{__DATE__} expands to
  1080. @code{@w{"??? ?? ????"}}.
  1081. We deprecate the use of @code{__DATE__} for the sake of reproducible
  1082. compilation.
  1083. @item __TIME__
  1084. This macro expands to a string constant that describes the time of
  1085. compilation. The string constant contains eight characters and looks
  1086. like @code{"23:59:01"}.
  1087. If the compiler cannot determine the current time, it emits a warning
  1088. message (once per compilation) and @code{__TIME__} expands to
  1089. @code{"??:??:??"}.
  1090. We deprecate the use of @code{__TIME__} for the sake of reproducible
  1091. compilation.
  1092. @item __STDC__
  1093. In normal operation, this macro expands to the constant 1, to signify
  1094. that this compiler implements ISO Standard C@.
  1095. @item __STDC_VERSION__
  1096. This macro expands to the C Standard's version number, a long integer
  1097. constant of the form @code{@var{yyyy}@var{mm}L} where @var{yyyy} and
  1098. @var{mm} are the year and month of the Standard version. This states
  1099. which version of the C Standard the compiler implements.
  1100. The current default value is @code{201112L}, which signifies the C
  1101. 2011 standard.
  1102. @item __STDC_HOSTED__
  1103. This macro is defined, with value 1, if the compiler's target is a
  1104. @dfn{hosted environment}. A hosted environment provides the full
  1105. facilities of the standard C library.
  1106. @end table
  1107. The rest of the predefined macros are GNU C extensions.
  1108. @table @code
  1109. @item __COUNTER__
  1110. This macro expands to sequential integral values starting from 0. In
  1111. other words, each time the program uses this macro, it generates the
  1112. next successive integer. This, with the @code{##} operator, provides
  1113. a convenient means for macros to generate unique identifiers.
  1114. @item __GNUC__
  1115. @itemx __GNUC_MINOR__
  1116. @itemx __GNUC_PATCHLEVEL__
  1117. These macros expand to the major version, minor version, and patch
  1118. level of the compiler, as integer constants. For example, GCC 3.2.1
  1119. expands @code{__GNUC__} to 3, @code{__GNUC_MINOR__} to 2, and
  1120. @code{__GNUC_PATCHLEVEL__} to 1.
  1121. If all you need to know is whether or not your program is being
  1122. compiled by GCC, or a non-GCC compiler that claims to accept the GNU C
  1123. extensions, you can simply test @code{__GNUC__}. If you need to write
  1124. code that depends on a specific version, you must check more
  1125. carefully. Each change in the minor version resets the patch level to
  1126. zero; each change in the major version (which happens rarely) resets
  1127. the minor version and the patch level to zero. To use the predefined
  1128. macros directly in the conditional, write it like this:
  1129. @example
  1130. /* @r{Test for version 3.2.0 or later.} */
  1131. #if __GNUC__ > 3 || \
  1132. (__GNUC__ == 3 && (__GNUC_MINOR__ > 2 || \
  1133. (__GNUC_MINOR__ == 2 && \
  1134. __GNUC_PATCHLEVEL__ > 0))
  1135. @end example
  1136. @noindent
  1137. Another approach is to use the predefined macros to
  1138. calculate a single number, then compare that against a threshold:
  1139. @example
  1140. #define GCC_VERSION (__GNUC__ * 10000 \
  1141. + __GNUC_MINOR__ * 100 \
  1142. + __GNUC_PATCHLEVEL__)
  1143. /* @r{@dots{}} */
  1144. /* @r{Test for GCC > 3.2.0} */
  1145. #if GCC_VERSION > 30200
  1146. @end example
  1147. @noindent
  1148. Many people find this form easier to understand.
  1149. @item __VERSION__
  1150. This macro expands to a string constant that describes the version of
  1151. the compiler in use. You should not rely on its contents' having any
  1152. particular form, but you can count on it to contain at least the
  1153. release number.
  1154. @item __TIMESTAMP__
  1155. This macro expands to a string constant that describes the date and
  1156. time of the last modification of the current source file. The string
  1157. constant contains abbreviated day of the week, month, day of the
  1158. month, time in hh:mm:ss form, and the year, in the format
  1159. @code{@w{"Sun Sep 16 01:03:52 1973"}}. If the day of the month is
  1160. less than 10, it is padded with a space on the left.
  1161. If GCC cannot determine that information date, it emits a warning
  1162. message (once per compilation) and @code{__TIMESTAMP__} expands to
  1163. @code{@w{"??? ??? ?? ??:??:?? ????"}}.
  1164. We deprecate the use of this macro for the sake of reproducible
  1165. compilation.
  1166. @end table
  1167. @node Undefining and Redefining Macros
  1168. @subsection Undefining and Redefining Macros
  1169. @cindex undefining macros
  1170. @cindex redefining macros
  1171. @findex #undef
  1172. You can @dfn{undefine} a macro with the @code{#undef} directive.
  1173. @code{#undef} takes a single argument, the name of the macro to
  1174. undefine. You use the bare macro name, even if the macro is
  1175. function-like. It is an error if anything appears on the line after
  1176. the macro name. @code{#undef} has no effect if the name is not a
  1177. macro.
  1178. @example
  1179. #define FOO 4
  1180. x = FOO; @expansion{} x = 4;
  1181. #undef FOO
  1182. x = FOO; @expansion{} x = FOO;
  1183. @end example
  1184. Once a macro has been undefined, that identifier may be @dfn{redefined}
  1185. as a macro by a subsequent @code{#define} directive. The new definition
  1186. need not have any resemblance to the old definition.
  1187. You can define a macro again without first undefining it only if
  1188. the new definition is @dfn{effectively the same} as the old one.
  1189. Two macro definitions are effectively the same if:
  1190. @itemize @bullet
  1191. @item Both are the same type of macro (object- or function-like).
  1192. @item All the tokens of the replacement list are the same.
  1193. @item If there are any parameters, they are the same.
  1194. @item Whitespace appears in the same places in both. It need not be
  1195. exactly the same amount of whitespace, though. Remember that comments
  1196. count as whitespace.
  1197. @end itemize
  1198. @noindent
  1199. These definitions are effectively the same:
  1200. @example
  1201. #define FOUR (2 + 2)
  1202. #define FOUR (2 + 2)
  1203. #define FOUR (2 /* @r{two} */ + 2)
  1204. @end example
  1205. @noindent
  1206. but these are not:
  1207. @example
  1208. #define FOUR (2 + 2)
  1209. #define FOUR ( 2+2 )
  1210. #define FOUR (2 * 2)
  1211. #define FOUR(score,and,seven,years,ago) (2 + 2)
  1212. @end example
  1213. This allows two different header files to define a common macro.
  1214. You can redefine an existing macro with #define, but redefining an
  1215. existing macro name with a different definition results in a warning.
  1216. @node Directives Within Macro Arguments
  1217. @subsection Directives Within Macro Arguments
  1218. @cindex macro arguments and directives
  1219. GNU C permits and handles preprocessing directives in the text provided
  1220. as arguments for a macro. That case is undefined in the C standard.
  1221. but in GNU C@ conditional directives in macro arguments
  1222. are clear and valid.
  1223. A paradoxical case is to redefine a macro within the call to that same
  1224. macro. What happens is, the new definition takes effect in time for
  1225. pre-expansion of @emph{all} the arguments, then the original
  1226. definition is expanded to replace the call. Here is a pathological
  1227. example:
  1228. @example
  1229. #define f(x) x x
  1230. f (first f second
  1231. #undef f
  1232. #define f 2
  1233. f)
  1234. @end example
  1235. @noindent
  1236. which expands to
  1237. @example
  1238. first 2 second 2 first 2 second 2
  1239. @end example
  1240. @noindent
  1241. with the semantics described above. We suggest you avoid writing code
  1242. which does this sort of thing.
  1243. @node Macro Pitfalls
  1244. @subsection Macro Pitfalls
  1245. @cindex problems with macros
  1246. @cindex pitfalls of macros
  1247. In this section we describe some special rules that apply to macros and
  1248. macro expansion, and point out certain cases in which the rules have
  1249. counter-intuitive consequences that you must watch out for.
  1250. @menu
  1251. * Misnesting::
  1252. * Operator Precedence Problems::
  1253. * Swallowing the Semicolon::
  1254. * Duplication of Side Effects::
  1255. * Macros and Auto Type::
  1256. * Self-Referential Macros::
  1257. * Argument Prescan::
  1258. @end menu
  1259. @node Misnesting
  1260. @subsubsection Misnesting
  1261. When a macro is called with arguments, the arguments are substituted
  1262. into the macro body and the result is checked, together with the rest of
  1263. the input file, for more macro calls. It is possible to piece together
  1264. a macro call coming partially from the macro body and partially from the
  1265. arguments. For example,
  1266. @example
  1267. #define twice(x) (2*(x))
  1268. #define call_with_1(x) x(1)
  1269. call_with_1 (twice)
  1270. @expansion{} twice(1)
  1271. @expansion{} (2*(1))
  1272. @end example
  1273. Macro definitions do not have to have balanced parentheses. By writing
  1274. an unbalanced open parenthesis in a macro body, it is possible to create
  1275. a macro call that begins inside the macro body but ends outside of it.
  1276. For example,
  1277. @example
  1278. #define strange(file) fprintf (file, "%s %d",
  1279. /* @r{@dots{}} */
  1280. strange(stderr) p, 35)
  1281. @expansion{} fprintf (stderr, "%s %d", p, 35)
  1282. @end example
  1283. The ability to piece together a macro call can be useful, but the use of
  1284. unbalanced open parentheses in a macro body is just confusing, and
  1285. should be avoided.
  1286. @node Operator Precedence Problems
  1287. @subsubsection Operator Precedence Problems
  1288. @cindex parentheses in macro bodies
  1289. You may have noticed that in most of the macro definition examples shown
  1290. above, each occurrence of a macro parameter name had parentheses around
  1291. it. In addition, another pair of parentheses usually surrounds the
  1292. entire macro definition. Here is why it is best to write macros that
  1293. way.
  1294. Suppose you define a macro as follows,
  1295. @example
  1296. #define ceil_div(x, y) (x + y - 1) / y
  1297. @end example
  1298. @noindent
  1299. whose purpose is to divide, rounding up. (One use for this operation is
  1300. to compute how many @code{int} objects are needed to hold a certain
  1301. number of @code{char} objects.) Then suppose it is used as follows:
  1302. @example
  1303. a = ceil_div (b & c, sizeof (int));
  1304. @expansion{} a = (b & c + sizeof (int) - 1) / sizeof (int);
  1305. @end example
  1306. @noindent
  1307. This does not do what is intended. The operator-precedence rules of
  1308. C make it equivalent to this:
  1309. @example
  1310. a = (b & (c + sizeof (int) - 1)) / sizeof (int);
  1311. @end example
  1312. @noindent
  1313. What we want is this:
  1314. @example
  1315. a = ((b & c) + sizeof (int) - 1)) / sizeof (int);
  1316. @end example
  1317. @noindent
  1318. Defining the macro as
  1319. @example
  1320. #define ceil_div(x, y) ((x) + (y) - 1) / (y)
  1321. @end example
  1322. @noindent
  1323. provides the desired result.
  1324. Unintended grouping can result in another way. Consider @code{sizeof
  1325. ceil_div(1, 2)}. That has the appearance of a C expression that would
  1326. compute the size of the type of @code{ceil_div (1, 2)}, but in fact it
  1327. means something very different. Here is what it expands to:
  1328. @example
  1329. sizeof ((1) + (2) - 1) / (2)
  1330. @end example
  1331. @noindent
  1332. This would take the size of an integer and divide it by two. The
  1333. precedence rules have put the division outside the @code{sizeof} when it
  1334. was intended to be inside.
  1335. Parentheses around the entire macro definition prevent such problems.
  1336. Here, then, is the recommended way to define @code{ceil_div}:
  1337. @example
  1338. #define ceil_div(x, y) (((x) + (y) - 1) / (y))
  1339. @end example
  1340. @node Swallowing the Semicolon
  1341. @subsubsection Swallowing the Semicolon
  1342. @cindex semicolons (after macro calls)
  1343. Often it is desirable to define a macro that expands into a compound
  1344. statement. Consider, for example, the following macro, that advances a
  1345. pointer (the parameter @code{p} says where to find it) across whitespace
  1346. characters:
  1347. @example
  1348. #define SKIP_SPACES(p, limit) \
  1349. @{ char *lim = (limit); \
  1350. while (p < lim) @{ \
  1351. if (*p++ != ' ') @{ \
  1352. p--; break; @}@}@}
  1353. @end example
  1354. @noindent
  1355. Here backslash-newline is used to split the macro definition, which must
  1356. be a single logical line, so that it resembles the way such code would
  1357. be laid out if not part of a macro definition.
  1358. A call to this macro might be @code{SKIP_SPACES (p, lim)}. Strictly
  1359. speaking, the call expands to a compound statement, which is a complete
  1360. statement with no need for a semicolon to end it. However, since it
  1361. looks like a function call, it minimizes confusion if you can use it
  1362. like a function call, writing a semicolon afterward, as in
  1363. @code{SKIP_SPACES (p, lim);}
  1364. This can cause trouble before @code{else} statements, because the
  1365. semicolon is actually a null statement. Suppose you write
  1366. @example
  1367. if (*p != 0)
  1368. SKIP_SPACES (p, lim);
  1369. else /* @r{@dots{}} */
  1370. @end example
  1371. @noindent
  1372. The presence of two statements---the compound statement and a null
  1373. statement---in between the @code{if} condition and the @code{else}
  1374. makes invalid C code.
  1375. The definition of the macro @code{SKIP_SPACES} can be altered to solve
  1376. this problem, using a @code{do @r{@dots{}} while} statement. Here is how:
  1377. @example
  1378. #define SKIP_SPACES(p, limit) \
  1379. do @{ char *lim = (limit); \
  1380. while (p < lim) @{ \
  1381. if (*p++ != ' ') @{ \
  1382. p--; break; @}@}@} \
  1383. while (0)
  1384. @end example
  1385. Now @code{SKIP_SPACES (p, lim);} expands into
  1386. @example
  1387. do @{ /* @r{@dots{}} */ @} while (0);
  1388. @end example
  1389. @noindent
  1390. which is one statement. The loop executes exactly once; most compilers
  1391. generate no extra code for it.
  1392. @node Duplication of Side Effects
  1393. @subsubsection Duplication of Side Effects
  1394. @cindex side effects (in macro arguments)
  1395. @cindex unsafe macros
  1396. Many C programs define a macro @code{min}, for ``minimum'', like this:
  1397. @example
  1398. #define min(X, Y) ((X) < (Y) ? (X) : (Y))
  1399. @end example
  1400. When you use this macro with an argument containing a side effect,
  1401. as shown here,
  1402. @example
  1403. next = min (x + y, foo (z));
  1404. @end example
  1405. @noindent
  1406. it expands as follows:
  1407. @example
  1408. next = ((x + y) < (foo (z)) ? (x + y) : (foo (z)));
  1409. @end example
  1410. @noindent
  1411. where @code{x + y} has been substituted for @code{X} and @code{foo (z)}
  1412. for @code{Y}.
  1413. The function @code{foo} is used only once in the statement as it
  1414. appears in the program, but the expression @code{foo (z)} has been
  1415. substituted twice into the macro expansion. As a result, @code{foo}
  1416. might be called twice when the statement is executed. If it has side
  1417. effects or if it takes a long time to compute, that may be
  1418. undesirable. We say that @code{min} is an @dfn{unsafe} macro.
  1419. The best solution to this problem is to define @code{min} in a way that
  1420. computes the value of @code{foo (z)} only once. In general, that requires
  1421. using @code{__auto_type} (@pxref{Auto Type}). How to use it for this
  1422. is described in the following section. @xref{Macros and Auto Type}.
  1423. Otherwise, you will need to be careful when @emph{using} the macro
  1424. @code{min}. For example, you can calculate the value of @code{foo
  1425. (z)}, save it in a variable, and use that variable in @code{min}:
  1426. @example
  1427. @group
  1428. #define min(X, Y) ((X) < (Y) ? (X) : (Y))
  1429. /* @r{@dots{}} */
  1430. @{
  1431. int tem = foo (z);
  1432. next = min (x + y, tem);
  1433. @}
  1434. @end group
  1435. @end example
  1436. @noindent
  1437. (where we assume that @code{foo} returns type @code{int}).
  1438. When the repeated value appears as the condition of the @code{?:}
  1439. operator and again as its @var{iftrue} expression, you can avoid
  1440. repeated execution by omitting the @var{iftrue} expression, like this:
  1441. @example
  1442. #define x_or_y(X, Y) ((X) ? : (Y))
  1443. @end example
  1444. @noindent
  1445. In GNU C, this expands to use the first macro argument's value if that
  1446. isn't zero. If that's zero, it compiles the second argument and uses
  1447. that value. @xref{Conditional Expression}.
  1448. @node Macros and Auto Type
  1449. @subsubsection Using @code{__auto_type} for Local Variables
  1450. @cindex local variables in macros
  1451. @cindex variables, local, in macros
  1452. @cindex macros, local variables in
  1453. The operator @code{__auto_type} makes it possible to
  1454. define macros that can work on any data type even though they need to
  1455. generate local variable declarations. @xref{Auto Type}.
  1456. For instance, here's how to define a safe ``maximum'' macro that
  1457. operates on any arithmetic type and computes each of its arguments
  1458. exactly once:
  1459. @example
  1460. #define max(a,b) \
  1461. (@{ __auto_type _a = (a); \
  1462. __auto_type _b = (b); \
  1463. _a > _b ? _a : _b; @})
  1464. @end example
  1465. The @samp{(@{ @dots{} @})} notation produces @dfn{statement
  1466. expression}---a statement that can be used as an expression
  1467. (@pxref{Statement Exprs}). Its value is the value of its last
  1468. statement. This permits us to define local variables and store each
  1469. argument value into one.
  1470. @cindex underscores in variables in macros
  1471. @cindex @samp{_} in variables in macros
  1472. The reason for using names that start with underscores for the local
  1473. variables is to avoid conflicts with variable names that occur within
  1474. the expressions that are substituted for @code{a} and @code{b}.
  1475. Underscore followed by a lower case letter won't be predefined by the
  1476. system in any way.
  1477. @c We hope someday to extend C with a new form of declaration syntax
  1478. @c which all the newly declared variables' scopes would begin at the end
  1479. @c of the entire declaration, rather than as soon as each variable's
  1480. @c declaration begins. This way, all the variables' initializers would
  1481. @c be interpreted in the context before the declaration. Then we could
  1482. @c use any names whatsoever for the local variables and always get correct
  1483. @c behavior for the macro.
  1484. @node Self-Referential Macros
  1485. @subsubsection Self-Referential Macros
  1486. @cindex self-reference
  1487. A @dfn{self-referential} macro is one whose name appears in its
  1488. definition. Recall that all macro definitions are rescanned for more
  1489. macros to replace. If the self-reference were considered a use of the
  1490. macro, it would produce an infinitely large expansion. To prevent
  1491. this, the self-reference is not considered a macro call: preprocessing
  1492. leaves it unchanged. Consider an example:
  1493. @example
  1494. #define foo (4 + foo)
  1495. @end example
  1496. @noindent
  1497. where @code{foo} is also a variable in your program.
  1498. Following the ordinary rules, each reference to @code{foo} will expand
  1499. into @code{(4 + foo)}; then this will be rescanned and will expand into
  1500. @code{(4 + (4 + foo))}; and so on until the computer runs out of memory.
  1501. The self-reference rule cuts this process short after one step, at
  1502. @code{(4 + foo)}. Therefore, this macro definition has the possibly
  1503. useful effect of causing the program to add 4 to the value of @code{foo}
  1504. wherever @code{foo} is referred to.
  1505. In most cases, it is a bad idea to take advantage of this feature. A
  1506. person reading the program who sees that @code{foo} is a variable will
  1507. not expect that it is a macro as well. The reader will come across the
  1508. identifier @code{foo} in the program and think its value should be that
  1509. of the variable @code{foo}, whereas in fact the value is four greater.
  1510. It is useful to make a macro definition that expands to the macro
  1511. name itself. If you write
  1512. @example
  1513. #define EPERM EPERM
  1514. @end example
  1515. @noindent
  1516. then the macro @code{EPERM} expands to @code{EPERM}. Effectively,
  1517. preprocessing leaves it unchanged in the source code. You can tell
  1518. that it's a macro with @code{#ifdef}. You might do this if you want
  1519. to define numeric constants with an @code{enum}, but have
  1520. @code{#ifdef} be true for each constant.
  1521. If a macro @code{x} expands to use a macro @code{y}, and the expansion of
  1522. @code{y} refers to the macro @code{x}, that is an @dfn{indirect
  1523. self-reference} of @code{x}. @code{x} is not expanded in this case
  1524. either. Thus, if we have
  1525. @example
  1526. #define x (4 + y)
  1527. #define y (2 * x)
  1528. @end example
  1529. @noindent
  1530. then @code{x} and @code{y} expand as follows:
  1531. @example
  1532. @group
  1533. x @expansion{} (4 + y)
  1534. @expansion{} (4 + (2 * x))
  1535. y @expansion{} (2 * x)
  1536. @expansion{} (2 * (4 + y))
  1537. @end group
  1538. @end example
  1539. @noindent
  1540. Each macro is expanded when it appears in the definition of the other
  1541. macro, but not when it indirectly appears in its own definition.
  1542. @node Argument Prescan
  1543. @subsubsection Argument Prescan
  1544. @cindex expansion of arguments
  1545. @cindex macro argument expansion
  1546. @cindex prescan of macro arguments
  1547. Macro arguments are completely macro-expanded before they are
  1548. substituted into a macro body, unless they are stringified or pasted
  1549. with other tokens. After substitution, the entire macro body, including
  1550. the substituted arguments, is scanned again for macros to be expanded.
  1551. The result is that the arguments are scanned @emph{twice} to expand
  1552. macro calls in them.
  1553. Most of the time, this has no effect. If the argument contained any
  1554. macro calls, they were expanded during the first scan. The result
  1555. therefore contains no macro calls, so the second scan does not change
  1556. it. If the argument were substituted as given, with no prescan, the
  1557. single remaining scan would find the same macro calls and produce the
  1558. same results.
  1559. You might expect the double scan to change the results when a
  1560. self-referential macro is used in an argument of another macro
  1561. (@pxref{Self-Referential Macros}): the self-referential macro would be
  1562. expanded once in the first scan, and a second time in the second scan.
  1563. However, this is not what happens. The self-references that do not
  1564. expand in the first scan are marked so that they will not expand in the
  1565. second scan either.
  1566. You might wonder, ``Why mention the prescan, if it makes no difference?
  1567. And why not skip it and make preprocessing go faster?'' The answer is
  1568. that the prescan does make a difference in three special cases:
  1569. @itemize @bullet
  1570. @item
  1571. Nested calls to a macro.
  1572. We say that @dfn{nested} calls to a macro occur when a macro's argument
  1573. contains a call to that very macro. For example, if @code{f} is a macro
  1574. that expects one argument, @code{f (f (1))} is a nested pair of calls to
  1575. @code{f}. The desired expansion is made by expanding @code{f (1)} and
  1576. substituting that into the definition of @code{f}. The prescan causes
  1577. the expected result to happen. Without the prescan, @code{f (1)} itself
  1578. would be substituted as an argument, and the inner use of @code{f} would
  1579. appear during the main scan as an indirect self-reference and would not
  1580. be expanded.
  1581. @item
  1582. Macros that call other macros that stringify or concatenate.
  1583. If an argument is stringified or concatenated, the prescan does not
  1584. occur. If you @emph{want} to expand a macro, then stringify or
  1585. concatenate its expansion, you can do that by causing one macro to call
  1586. another macro that does the stringification or concatenation. For
  1587. instance, if you have
  1588. @example
  1589. #define AFTERX(x) X_ ## x
  1590. #define XAFTERX(x) AFTERX(x)
  1591. #define TABLESIZE 1024
  1592. #define BUFSIZE TABLESIZE
  1593. @end example
  1594. @noindent
  1595. then @code{AFTERX(BUFSIZE)} expands to @code{X_BUFSIZE}, and
  1596. @code{XAFTERX(BUFSIZE)} expands to @code{X_1024}. (Not to
  1597. @code{X_TABLESIZE}. Prescan always does a complete expansion.)
  1598. @item
  1599. Macros used in arguments, whose expansions contain unshielded commas.
  1600. This can cause a macro expanded on the second scan to be called with the
  1601. wrong number of arguments. Here is an example:
  1602. @example
  1603. #define foo a,b
  1604. #define bar(x) lose(x)
  1605. #define lose(x) (1 + (x))
  1606. @end example
  1607. We would like @code{bar(foo)} to turn into @code{(1 + (foo))}, which
  1608. would then turn into @code{(1 + (a,b))}. Instead, @code{bar(foo)}
  1609. expands into @code{lose(a,b)}, which gives an error because @code{lose}
  1610. requires a single argument. In this case, the problem is easily solved
  1611. by the same parentheses that ought to be used to prevent misnesting of
  1612. arithmetic operations:
  1613. @example
  1614. #define foo (a,b)
  1615. @exdent or
  1616. #define bar(x) lose((x))
  1617. @end example
  1618. The extra pair of parentheses prevents the comma in @code{foo}'s
  1619. definition from being interpreted as an argument separator.
  1620. @end itemize
  1621. @ignore
  1622. @c This is commented out because pragmas are not supposed
  1623. @c to alter the meaning of the program.
  1624. @c Microsoft did something stupid in defining these.
  1625. @node Macro Pragmas
  1626. @subsection Macro Pragmas
  1627. A pragma is a way of specifying special directions to the C compiler.
  1628. @xref{Pragmas}, for the basic syntax of pragmas. Here we describe two
  1629. pragmas that save the current definition of a macro on a stack, and
  1630. restore it later. This makes it possible to redefine a macro temporarily
  1631. and later go back to the previous definition.
  1632. @table @code
  1633. @item #pragma push_macro (@var{macro_name})
  1634. @itemx _Pragma ("push_macro (@var{macro_name})")
  1635. The @samp{push_macro} pragma saves the current macro definition of
  1636. @var{macro_name} on the macro definition stack.
  1637. @item #pragma pop_macro (@var{macro_name})
  1638. @itemx _Pragma ("pop_macro (@var{macro_name})")
  1639. The @samp{pop_macro} pragma pops a saved macro definition
  1640. off the macro definition stack and defines @var{macro_name} with
  1641. that definition.
  1642. @end table
  1643. Each macro name has a separate stack, and @samp{pop_macro}
  1644. when the stack is empty has no effect.
  1645. Here's an example of using these to pragmas to override temporarily
  1646. the definition of @code{FOO}.
  1647. @example
  1648. #define FOO 42
  1649. /* @r{Do something with @var{FOO} defined as 42...} */
  1650. _Pragma ("push_macro (\"FOO\")")
  1651. #undef FOO
  1652. #define FOO 47
  1653. /* @r{Do something with @var{FOO} defined as 47...} */
  1654. _Pragma ("pop_macro (\"FOO\")")
  1655. /* @r{@var{FOO} is now restored}
  1656. @r{to its previous definition of 42.} */
  1657. @end example
  1658. @end ignore
  1659. @node Conditionals
  1660. @section Conditionals
  1661. @cindex conditionals
  1662. A @dfn{conditional} is a preprocessing directive that controls whether
  1663. or not to include a chunk of code in the final token stream that is
  1664. compiled. Preprocessing conditionals can test arithmetic expressions,
  1665. or whether a name is defined as a macro, or both together using the
  1666. special @code{defined} operator.
  1667. A preprocessing conditional in C resembles in some ways an @code{if}
  1668. statement in C, but it is important to understand the difference between
  1669. them. The condition in an @code{if} statement is tested during the
  1670. execution of your program. Its purpose is to allow your program to
  1671. behave differently from run to run, depending on the data it is
  1672. operating on. The condition in a preprocessing conditional directive is
  1673. tested when your program is compiled. Its purpose is to allow different
  1674. code to be included in the program depending on the situation at the
  1675. time of compilation.
  1676. Sometimes this distinction makes no practical difference. GCC and
  1677. other modern compilers often
  1678. do test @code{if} statements when a program is compiled, if their
  1679. conditions are known not to vary at run time, and eliminate code that
  1680. can never be executed. If you can count on your compiler to do this,
  1681. you may find that your program is more readable if you use @code{if}
  1682. statements with constant conditions (perhaps determined by macros). Of
  1683. course, you can only use this to exclude code, not type definitions or
  1684. other preprocessing directives, and you can only do it if the file
  1685. remains syntactically valid when that code is not used.
  1686. @menu
  1687. * Conditional Uses::
  1688. * Conditional Syntax::
  1689. * Deleted Code::
  1690. @end menu
  1691. @node Conditional Uses
  1692. @subsection Uses of Conditional Directives
  1693. There are three usual reasons to use a preprocessing conditional.
  1694. @itemize @bullet
  1695. @item
  1696. A program may need to use different code depending on the machine or
  1697. operating system it is to run on. In some cases the code for one
  1698. operating system may be erroneous on another operating system; for
  1699. example, it might refer to data types or constants that do not exist on
  1700. the other system. When this happens, it is not enough to avoid
  1701. executing the invalid code. Its mere presence will cause the compiler
  1702. to reject the program. With a preprocessing conditional, the offending
  1703. code can be effectively excised from the program when it is not valid.
  1704. @item
  1705. You may want to be able to compile the same source file into two
  1706. different programs. One version might make frequent time-consuming
  1707. consistency checks on its intermediate data, or print the values of
  1708. those data for debugging, and the other not.
  1709. @item
  1710. A conditional whose condition is always false is one way to exclude code
  1711. from the program but keep it as a sort of comment for future reference.
  1712. @end itemize
  1713. Simple programs that do not need system-specific logic or complex
  1714. debugging hooks generally will not need to use preprocessing
  1715. conditionals.
  1716. @node Conditional Syntax
  1717. @subsection Syntax of Preprocessing Conditionals
  1718. @findex #if
  1719. A preprocessing conditional begins with a @dfn{conditional
  1720. directive}: @code{#if}, @code{#ifdef} or @code{#ifndef}.
  1721. @menu
  1722. * ifdef::
  1723. * if::
  1724. * defined::
  1725. * else::
  1726. * elif::
  1727. @end menu
  1728. @node ifdef
  1729. @subsubsection The @code{#ifdef} directive
  1730. @findex #ifdef
  1731. @findex #endif
  1732. The simplest sort of conditional is
  1733. @example
  1734. @group
  1735. #ifdef @var{MACRO}
  1736. @var{controlled text}
  1737. #endif /* @var{MACRO} */
  1738. @end group
  1739. @end example
  1740. @cindex conditional group
  1741. This block is called a @dfn{conditional group}. The body,
  1742. @var{controlled text}, will be included in compilation if
  1743. and only if @var{MACRO} is defined. We say that the conditional
  1744. @dfn{succeeds} if @var{MACRO} is defined, @dfn{fails} if it is not.
  1745. The @var{controlled text} inside a conditional can include
  1746. preprocessing directives. They are executed only if the conditional
  1747. succeeds. You can nest conditional groups inside other conditional
  1748. groups, but they must be completely nested. In other words,
  1749. @code{#endif} always matches the nearest @code{#ifdef} (or
  1750. @code{#ifndef}, or @code{#if}). Also, you cannot start a conditional
  1751. group in one file and end it in another.
  1752. Even if a conditional fails, the @var{controlled text} inside it is
  1753. still run through initial transformations and tokenization. Therefore,
  1754. it must all be lexically valid C@. Normally the only way this matters is
  1755. that all comments and string literals inside a failing conditional group
  1756. must still be properly ended.
  1757. The comment following the @code{#endif} is not required, but it is a
  1758. good practice if there is a lot of @var{controlled text}, because it
  1759. helps people match the @code{#endif} to the corresponding @code{#ifdef}.
  1760. Older programs sometimes put @var{macro} directly after the
  1761. @code{#endif} without enclosing it in a comment. This is invalid code
  1762. according to the C standard, but it only causes a warning in GNU C@.
  1763. It never affects which @code{#ifndef} the @code{#endif} matches.
  1764. @findex #ifndef
  1765. Sometimes you wish to use some code if a macro is @emph{not} defined.
  1766. You can do this by writing @code{#ifndef} instead of @code{#ifdef}.
  1767. One common use of @code{#ifndef} is to include code only the first
  1768. time a header file is included. @xref{Once-Only Headers}.
  1769. Macro definitions can vary between compilations for several reasons.
  1770. Here are some samples.
  1771. @itemize @bullet
  1772. @item
  1773. Some macros are predefined on each kind of machine
  1774. (@pxref{System-specific Predefined Macros, System-specific Predefined
  1775. Macros, System-specific Predefined Macros, gcc, Using the GNU Compiler
  1776. Collection}). This allows you to provide code specially tuned for a
  1777. particular machine.
  1778. @item
  1779. System header files define more macros, associated with the features
  1780. they implement. You can test these macros with conditionals to avoid
  1781. using a system feature on a machine where it is not implemented.
  1782. @item
  1783. Macros can be defined or undefined with the @option{-D} and @option{-U}
  1784. command-line options when you compile the program. You can arrange to
  1785. compile the same source file into two different programs by choosing a
  1786. macro name to specify which program you want, writing conditionals to
  1787. test whether or how this macro is defined, and then controlling the
  1788. state of the macro with command-line options, perhaps set in the
  1789. file @file{Makefile}. @xref{Invocation, Invoking GCC, Invoking GCC,
  1790. gcc, Using the GNU Compiler Collection}.
  1791. @item
  1792. Your program might have a special header file (often called
  1793. @file{config.h}) that is adjusted when the program is compiled. It can
  1794. define or not define macros depending on the features of the system and
  1795. the desired capabilities of the program. The adjustment can be
  1796. automated by a tool such as @command{autoconf}, or done by hand.
  1797. @end itemize
  1798. @node if
  1799. @subsubsection The @code{#if} directive
  1800. The @code{#if} directive allows you to test the value of an integer arithmetic
  1801. expression, rather than the mere existence of one macro. Its syntax is
  1802. @example
  1803. @group
  1804. #if @var{expression}
  1805. @var{controlled text}
  1806. #endif /* @var{expression} */
  1807. @end group
  1808. @end example
  1809. @var{expression} is a C expression of integer type, subject to
  1810. stringent restrictions so its value can be computed at compile time.
  1811. It may contain
  1812. @itemize @bullet
  1813. @item
  1814. Integer constants.
  1815. @item
  1816. Character constants, which are interpreted as they would be in normal
  1817. code.
  1818. @item
  1819. Arithmetic operators for addition, subtraction, multiplication,
  1820. division, bitwise operations, shifts, comparisons, and logical
  1821. operations (@code{&&} and @code{||}). The latter two obey the usual
  1822. short-circuiting rules of standard C@.
  1823. @item
  1824. Macros. All macros in the expression are expanded before actual
  1825. computation of the expression's value begins.
  1826. @item
  1827. Uses of the @code{defined} operator, which lets you check whether macros
  1828. are defined in the middle of an @code{#if}.
  1829. @item
  1830. Identifiers that are not macros, which are all considered to be the
  1831. number zero. This allows you to write @code{@w{#if MACRO}} instead of
  1832. @code{@w{#ifdef MACRO}}, if you know that MACRO, when defined, will
  1833. always have a nonzero value. Function-like macros used without their
  1834. function call parentheses are also treated as zero.
  1835. In some contexts this shortcut is undesirable. The @option{-Wundef}
  1836. requests warnings for any identifier in an @code{#if} that is not
  1837. defined as a macro.
  1838. @end itemize
  1839. Preprocessing does not know anything about the data types of C.
  1840. Therefore, @code{sizeof} operators are not recognized in @code{#if};
  1841. @code{sizeof} is simply an identifier, and if it is not a macro, it
  1842. stands for zero. This is likely to make the expression invalid.
  1843. Preprocessing does not recognize @code{enum} constants; they too are
  1844. simply identifiers, so if they are not macros, they stand for zero.
  1845. Preprocessing calculates the value of @var{expression}, and carries
  1846. out all calculations in the widest integer type known to the compiler;
  1847. on most machines supported by GNU C this is 64 bits. This is not the
  1848. same rule as the compiler uses to calculate the value of a constant
  1849. expression, and may give different results in some cases. If the
  1850. value comes out to be nonzero, the @code{#if} succeeds and the
  1851. @var{controlled text} is compiled; otherwise it is skipped.
  1852. @node defined
  1853. @subsubsection The @code{defined} test
  1854. @cindex @code{defined}
  1855. The special operator @code{defined} is used in @code{#if} and
  1856. @code{#elif} expressions to test whether a certain name is defined as a
  1857. macro. @code{defined @var{name}} and @code{defined (@var{name})} are
  1858. both expressions whose value is 1 if @var{name} is defined as a macro at
  1859. the current point in the program, and 0 otherwise. Thus, @code{@w{#if
  1860. defined MACRO}} is precisely equivalent to @code{@w{#ifdef MACRO}}.
  1861. @code{defined} is useful when you wish to test more than one macro for
  1862. existence at once. For example,
  1863. @example
  1864. #if defined (__arm__) || defined (__PPC__)
  1865. @end example
  1866. @noindent
  1867. would succeed if either of the names @code{__arm__} or
  1868. @code{__PPC__} is defined as a macro---in other words,
  1869. when compiling for ARM processors or PowerPC processors.
  1870. Conditionals written like this:
  1871. @example
  1872. #if defined BUFSIZE && BUFSIZE >= 1024
  1873. @end example
  1874. @noindent
  1875. can generally be simplified to just @code{@w{#if BUFSIZE >= 1024}},
  1876. since if @code{BUFSIZE} is not defined, it will be interpreted as having
  1877. the value zero.
  1878. In GCC, you can include @code{defined} as part of another macro definition,
  1879. like this:
  1880. @example
  1881. #define MACRO_DEFINED(X) defined X
  1882. #if MACRO_DEFINED(BUFSIZE)
  1883. @end example
  1884. @noindent
  1885. which would expand the @code{#if} expression to:
  1886. @example
  1887. #if defined BUFSIZE
  1888. @end example
  1889. @noindent
  1890. Generating @code{defined} in this way is a GNU C extension.
  1891. @node else
  1892. @subsubsection The @code{#else} directive
  1893. @findex #else
  1894. The @code{#else} directive can be added to a conditional to provide
  1895. alternative text to be used if the condition fails. This is what it
  1896. looks like:
  1897. @example
  1898. @group
  1899. #if @var{expression}
  1900. @var{text-if-true}
  1901. #else /* Not @var{expression} */
  1902. @var{text-if-false}
  1903. #endif /* Not @var{expression} */
  1904. @end group
  1905. @end example
  1906. @noindent
  1907. If @var{expression} is nonzero, the @var{text-if-true} is included and
  1908. the @var{text-if-false} is skipped. If @var{expression} is zero, the
  1909. opposite happens.
  1910. You can use @code{#else} with @code{#ifdef} and @code{#ifndef}, too.
  1911. @node elif
  1912. @subsubsection The @code{#elif} directive
  1913. @findex #elif
  1914. One common case of nested conditionals is used to check for more than two
  1915. possible alternatives. For example, you might have
  1916. @example
  1917. #if X == 1
  1918. /* @r{@dots{}} */
  1919. #else /* X != 1 */
  1920. #if X == 2
  1921. /* @r{@dots{}} */
  1922. #else /* X != 2 */
  1923. /* @r{@dots{}} */
  1924. #endif /* X != 2 */
  1925. #endif /* X != 1 */
  1926. @end example
  1927. Another conditional directive, @code{#elif}, allows this to be
  1928. abbreviated as follows:
  1929. @example
  1930. #if X == 1
  1931. /* @r{@dots{}} */
  1932. #elif X == 2
  1933. /* @r{@dots{}} */
  1934. #else /* X != 2 and X != 1*/
  1935. /* @r{@dots{}} */
  1936. #endif /* X != 2 and X != 1*/
  1937. @end example
  1938. @code{#elif} stands for ``else if''. Like @code{#else}, it goes in the
  1939. middle of a conditional group and subdivides it; it does not require a
  1940. matching @code{#endif} of its own. Like @code{#if}, the @code{#elif}
  1941. directive includes an expression to be tested. The text following the
  1942. @code{#elif} is processed only if the original @code{#if}-condition
  1943. failed and the @code{#elif} condition succeeds.
  1944. More than one @code{#elif} can go in the same conditional group. Then
  1945. the text after each @code{#elif} is processed only if the @code{#elif}
  1946. condition succeeds after the original @code{#if} and all previous
  1947. @code{#elif} directives within it have failed.
  1948. @code{#else} is allowed after any number of @code{#elif} directives, but
  1949. @code{#elif} may not follow @code{#else}.
  1950. @node Deleted Code
  1951. @subsection Deleted Code
  1952. @cindex commenting out code
  1953. If you replace or delete a part of the program but want to keep the
  1954. old code in the file for future reference, commenting it out is not so
  1955. straightforward in C. Block comments do not nest, so the first
  1956. comment inside the old code will end the commenting-out. The probable
  1957. result is a flood of syntax errors.
  1958. One way to avoid this problem is to use an always-false conditional
  1959. instead. For instance, put @code{#if 0} before the deleted code and
  1960. @code{#endif} after it. This works even if the code being turned
  1961. off contains conditionals, but they must be entire conditionals
  1962. (balanced @code{#if} and @code{#endif}).
  1963. Some people use @code{#ifdef notdef} instead. This is risky, because
  1964. @code{notdef} might be accidentally defined as a macro, and then the
  1965. conditional would succeed. @code{#if 0} can be counted on to fail.
  1966. Do not use @code{#if 0} around text that is not C code. Use a real
  1967. comment, instead. The interior of @code{#if 0} must consist of complete
  1968. tokens; in particular, single-quote characters must balance. Comments
  1969. often contain unbalanced single-quote characters (known in English as
  1970. apostrophes). These confuse @code{#if 0}. They don't confuse
  1971. @samp{/*}.
  1972. @node Diagnostics
  1973. @section Diagnostics
  1974. @cindex diagnostic
  1975. @cindex reporting errors
  1976. @cindex reporting warnings
  1977. @findex #error
  1978. The directive @code{#error} reports a fatal error. The
  1979. tokens forming the rest of the line following @code{#error} are used
  1980. as the error message.
  1981. The usual place to use @code{#error} is inside a conditional that
  1982. detects a combination of parameters that you know the program does not
  1983. properly support. For example,
  1984. @smallexample
  1985. #if !defined(UNALIGNED_INT_ASM_OP) && defined(DWARF2_DEBUGGING_INFO)
  1986. #error "DWARF2_DEBUGGING_INFO requires UNALIGNED_INT_ASM_OP."
  1987. #endif
  1988. @end smallexample
  1989. @findex #warning
  1990. The directive @code{#warning} is like @code{#error}, but it reports a
  1991. warning instead of an error. The tokens following @code{#warning} are
  1992. used as the warning message.
  1993. You might use @code{#warning} in obsolete header files, with a message
  1994. saying which header file to use instead.
  1995. Neither @code{#error} nor @code{#warning} macro-expands its argument.
  1996. Internal whitespace sequences are each replaced with a single space.
  1997. The line must consist of complete tokens. It is wisest to make the
  1998. argument of these directives be a single string constant; this avoids
  1999. problems with apostrophes and the like.
  2000. @node Line Control
  2001. @section Line Control
  2002. @cindex line control
  2003. Due to C's widespread availability and low-level nature, it is often
  2004. used as the target language for translation of other languages, or for
  2005. the output of lexical analyzers and parsers (e.g., lex/flex and
  2006. yacc/bison). Line control enables the user to track diagnostics back
  2007. to the location in the original language.
  2008. The C compiler knows the location in the source file where each token
  2009. came from: file name, starting line and column, and final line and column.
  2010. (Column numbers are used only for error messages.)
  2011. When a program generates C source code, as the Bison parser generator
  2012. does, often it copies some of that C code from another file. For
  2013. instance parts of the output from Bison are generated from scratch or
  2014. come from a standard parser file, but Bison copies the rest from
  2015. Bison's input file. Errors in that code, at compile time or run time,
  2016. should refer to that file, which is the real source code. To make that happen,
  2017. Bison generates line-control directives that the C compiler understands.
  2018. @findex #line
  2019. @code{#line} is a directive that specifies the original line number
  2020. and source file name for subsequent code. @code{#line} has three
  2021. variants:
  2022. @table @code
  2023. @item #line @var{linenum}
  2024. @var{linenum} is a non-negative decimal integer constant. It specifies
  2025. the line number that should be reported for the following line of
  2026. input. Subsequent lines are counted from @var{linenum}.
  2027. @item #line @var{linenum} @var{filename}
  2028. @var{linenum} is the same as for the first form, and has the same
  2029. effect. In addition, @var{filename} is a string constant that
  2030. specifies the source file name. Subsequent source lines are recorded
  2031. as coming from that file, until something else happens to change that.
  2032. @var{filename} is interpreted according to the normal rules for a
  2033. string constant. Backslash escapes are interpreted, in contrast to
  2034. @code{#include}.
  2035. @item #line @var{anything else}
  2036. @var{anything else} is checked for macro calls, which are expanded.
  2037. The result should match one of the above two forms.
  2038. @end table
  2039. @code{#line} directives alter the results of the @code{__FILE__} and
  2040. @code{__LINE__} symbols from that point on. @xref{Predefined Macros}.
  2041. @node Null Directive
  2042. @section Null Directive
  2043. @cindex null directive
  2044. The @dfn{null directive} consists of a @code{#} followed by a newline,
  2045. with only whitespace and comments in between. It has no
  2046. effect on the output of the compiler.