cpp.info 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  1. Info file cpp, produced by texinfo-format-buffer -*-Text-*-
  2. from file cpp.texinfo
  3. This file documents the GNU C Preprocessor.
  4. Copyright (C) 1987 Richard M. Stallman.
  5. Permission is granted to make and distribute verbatim copies of
  6. this manual provided the copyright notice and this permission notice
  7. are preserved on all copies.
  8. Permission is granted to copy and distribute modified versions of this
  9. manual under the conditions for verbatim copying, provided also that
  10. the entire resulting derived work is distributed under the terms of a
  11. permission notice identical to this one.
  12. Permission is granted to copy and distribute translations of this manual
  13. into another language, under the above conditions for modified versions.
  14. 
  15. File: cpp Node: Top, Up: (DIR), Next: Global Actions
  16. The C Preprocessor
  17. ******************
  18. The C preprocessor is a "macro processor" that is used automatically by
  19. the C compiler to transform your program before actual compilation. It is
  20. called a macro processor because it allows you to define "macros",
  21. which are brief abbreviations for longer constructs.
  22. The C preprocessor provides four separate facilities that you can use as
  23. you see fit:
  24. * Inclusion of header files. These are files of declarations that can be
  25. substituted into your program.
  26. * Macro expansion. You can define "macros", which are abbreviations
  27. for arbitrary fragments of C code, and then the C preprocessor will
  28. replace the macros with their definitions throughout the program.
  29. * Conditional compilation. Using special preprocessor commands, you
  30. can include or exclude parts of the program according to various
  31. conditions.
  32. * Line control. If you use a program to combine or rearrange source files into
  33. an intermediate file which is then compiled, you can use line control
  34. to inform the compiler of where each source line originally came from.
  35. C preprocessors vary in some details. This manual discusses the GNU C
  36. preprocessor, the C Compatible Compiler Preprocessor. The GNU C
  37. preprocessor provides a superset of the features of ANSI Standard C.
  38. ANSI Standard C requires the rejection of many harmless constructs commonly
  39. used by today's C programs. Such incompatibility would be inconvenient for
  40. users, so the GNU C preprocessor is configured to accept these constructs
  41. by default. Strictly speaking, to get ANSI Standard C, you must use the
  42. switches `-T', `-undef' and `-pedantic', but in practice the
  43. consequences of having strict ANSI Standard C make it undesirable to do
  44. this. *Note Invocation::.
  45. * Menu:
  46. * Global Actions:: Actions made uniformly on all input files.
  47. * Commands:: General syntax of preprocessor commands.
  48. * Header Files:: How and why to use header files.
  49. * Macros:: How and why to use macros.
  50. * Conditionals:: How and why to use conditionals.
  51. * Combining Sources:: Use of line control when you combine source files.
  52. * Other Commands:: Miscellaneous preprocessor commands.
  53. * Output:: Format of output from the C preprocessor.
  54. * Invocation:: How to invoke the preprocessor; command switches.
  55. * Concept Index:: Index of concepts and terms.
  56. * Index:: Index of commands, predefined macros and switches.
  57. 
  58. File: cpp Node: Global Actions, Prev: Top, Up: Top, Next: Commands
  59. Transformations Made Globally
  60. =============================
  61. Most C preprocessor features are inactive unless you give specific commands
  62. to request their use. (Preprocessor commands are lines starting with
  63. `#'; *Note Commands::). But there are three transformations that the
  64. preprocessor always makes on all the input it receives, even in the absence
  65. of commands.
  66. * All C comments are replaced with single spaces.
  67. * Backslash-Newline sequences are deleted, no matter where. This
  68. feature allows you to break long lines for cosmetic purposes without
  69. changing their meaning.
  70. * Predefined macro names are replaced with their expansions
  71. (*Note Predefined::).
  72. The first two transformations are done *before* nearly all other parsing
  73. and before preprocessor commands are recognized. Thus, for example, you
  74. can split a line cosmetically with Backslash-Newline just about anywhere.
  75. Even
  76. #defi\
  77. ne FO\
  78. O 10\
  79. 20
  80. is equivalent into `#define FOO 1020'.
  81. But there are a few exceptions to both transformations.
  82. * C comments and predefined macro names are not recognized inside a
  83. `#include' command in which the file name is delimited with
  84. `<' and `>'.
  85. * C comments and predefined macro names are never recognized within a
  86. character or string constant. (Strictly speaking, this is the rule,
  87. not an exception, but it is worth noting here anyway.)
  88. * Backslash-Newline is not discarded if preceded by an odd number of
  89. additional Backslashes. This is because the Backslashes quote each
  90. other, leaving the Newline as an ordinary Newline.
  91. x\\
  92. y
  93. is an example of a Backslash-Newline that is preserved from deletion for
  94. this reason.
  95. 
  96. File: cpp Node: Commands, Prev: Global Actions, Up: Top, Next: Header Files
  97. Preprocessor Commands
  98. =====================
  99. Most preprocessor features are active only if you use preprocessor commands
  100. to request their use.
  101. Preprocessor commands are lines in your program that start with `#'.
  102. The `#' is followed by an identifier that is the "command name".
  103. For example, `#define' is the command that defines a macro.
  104. Whitespace is also allowed before and after the `#'.
  105. The set of valid command names is fixed. Programs cannot define new
  106. preprocessor commands.
  107. Some command names require arguments; these make up the rest of the command
  108. line and must be separated from the command name by whitespace. For example,
  109. `#define' must be followed by a macro name and the intended expansion
  110. of the macro.
  111. A preprocessor command cannot be more than one line in normal circumstances.
  112. It may be split cosmetically with Backslash-Newline, but that has no effect
  113. on its meaning. Comments containing Newlines can also divide the command into
  114. multiple lines, but the comments are changed to Spaces before the command
  115. is interpreted. The only way a significant Newline can occur in a preprocessor
  116. command is within a string constant or character constant. Note that
  117. most C compilers that might be applied to the output from the preprocessor
  118. do not accept string or character constants containing Newlines.
  119. The `#' and the command name cannot come from a macro expansion. For
  120. example, if `foo' is defined as a macro expanding to `define',
  121. that does not make `#foo' a valid preprocessor command.
  122. 
  123. File: cpp Node: Header Files, Prev: Commands, Up: Top, Next: Macros
  124. Header Files
  125. ============
  126. A header file is a file containing C declarations and macro definitions
  127. (*Note Macros::) to be shared between several source files. You request
  128. the use of a header file in your program with the C preprocessor command
  129. `#include'.
  130. 
  131. File: cpp Node: Header Uses, Prev: Header Files, Up: Header Files, Next: Include Syntax
  132. Uses of Header Files
  133. --------------------
  134. Header files serve two kinds of purposes.
  135. * System header files declare the interfaces to parts of the operating
  136. system. You include them in your program to supply the definitions
  137. you need to invoke system calls and libraries.
  138. * Your own header files contain declarations for interfaces between the
  139. source files of your program. Each time you have a group of related
  140. declarations and macro definitions all or most of which are needed in
  141. several different source files, it is a good idea to create a header
  142. file for them.
  143. Including a header file produces the same results in C compilation as
  144. copying the header file into each source file that needs it. But such
  145. copying would be time-consuming and error-prone. With a header file, the
  146. related declarations appear in only one place. If they need to be changed,
  147. they can be changed in one place, and programs that include the header file
  148. will automatically use the new version when next recompiled. The header
  149. file eliminates the labor of finding and changing all the copies as well as
  150. the risk that a failure to find one copy will result in inconsistencies
  151. within a program.
  152. The usual convention is to give header files names that end with `.h'.
  153. 
  154. File: cpp Node: Include Syntax, Prev: Header Uses, Up: Header Files, Next: Include Operation
  155. The `#include' Command
  156. ----------------------
  157. Both user and system header files are included using the preprocessor
  158. command `#include'. It has three variants:
  159. `#include <FILE>'
  160. This variant is used for system header files. It searches for a file
  161. named FILE in a standard list of system directories.
  162. {{how can the user find out about/control this list?}}
  163. The parsing of this form of `#include' is slightly special
  164. because comments are not recognized within the `<...>'.
  165. Thus, in `#include <x/*y>' the `/*' does not start a comment
  166. and the command specifies inclusion of a system header file named
  167. `x/*y'. Of course, a header file with such a name is unlikely to
  168. exist on Unix, where shell wildcard features would make it hard to
  169. manipulate.
  170. FILE may not contain a `>' character. It may, however,
  171. contain a `<' character.
  172. `#include "FILE"'
  173. This variant is used for header files of your own program. It
  174. searches for a file named FILE first in the current working
  175. directory, and then in a specified list of directories for user
  176. header files, and finally in the same directories used for system header
  177. files. The current working directory is tried first because it is
  178. presumed to be the location of the files of the program being
  179. compiled. The other directories for user header files are specified
  180. with the command switch `-I' (*Note Invocation::).
  181. FILE may not contain `"' characters unless they are
  182. preceded by Backslashes. Note, however, that such Backslashes are
  183. *not* discarded when searching for the file. None of the character
  184. escape sequences appropriate to string constants in C is processed;
  185. all Backslashes are significant. Thus, `#include "x\n\"y"'
  186. specifies a filename containing two Backslashes. It is not clear why
  187. this behavior is ever useful, but the ANSI standard specifies it.
  188. `#include ANYTHING ELSE'
  189. This variant is called a "computed #include". Any `#include'
  190. command whose argument does not fit the above two forms is a computed
  191. include. ANYTHING ELSE is checked for macro calls, which are
  192. expanded (*Note Macros::). When this is done, the result must fit
  193. one of the above two variants.
  194. This feature allows you to define a macro which controls the file name
  195. to be used at a later point in the program. One application of this
  196. is to allow a site-configuration file for your program to specify the
  197. names of the system include files to be used. This can help in
  198. porting the program to various operating systems in which the
  199. necessary system header files are found in different places.
  200. 
  201. File: cpp Node: Include Operation, Prev: Include Syntax, Up: Header Files
  202. How `#include' Works
  203. --------------------
  204. The `#include' command works by directing the C preprocessor to scan
  205. the specified file as input before continuing with the rest of the current
  206. file. The output from the preprocessor contains the output already
  207. generated, followed by the output resulting from the included file,
  208. followed by the output that comes from the text after the `#include'
  209. command. For example, given two files as follows:
  210. /* File program.c */
  211. int x;
  212. #include "header.h"
  213. main ()
  214. {
  215. printf (test ());
  216. }
  217. /* File header.h */
  218. char *test ();
  219. the output generated by the C preprocessor for `program.c' as input
  220. would be
  221. int x;
  222. char *test ();
  223. main ()
  224. {
  225. printf (test ());
  226. }
  227. Included files are not limited to declarations and macro definitions; they
  228. are merely the typical use. Any fragment of a C program can be included
  229. from another file. The include file could even contain the beginning of a
  230. statement that is concluded in the containing file, or the end of a
  231. statement that was started in the including file. However, a comment or a
  232. string or character constant may not start in the included file and finish
  233. in the including file. An unterminated comment, string constant or
  234. character constant in an included file is considered to end (with an error
  235. message) at the end of the file.
  236. The line following the `#include' command is always treated as a
  237. separate line by the C preprocessor even if the included file lacks a final
  238. newline.
  239. 
  240. File: cpp Node: Macros, Prev: Header Files, Up: Top, Next: Conditionals
  241. Macros
  242. ======
  243. A macro is a sort of abbreviation which you can define once and then
  244. use later. There are many complicated features associated with macros
  245. in the C preprocessor.
  246. * Menu:
  247. * Simple Macros:: Macros that always expand the same way.
  248. * Argument Macros:: Macros that accept arguments that are substituted
  249. into the macro expansion.
  250. * Predefined:: Predefined macros that are always available.
  251. * Stringification:: Macro arguments converted into string constants.
  252. * Concatenation:: Building tokens from parts taken from macro arguments.
  253. * Undefining:: Cancelling a macro's definition.
  254. * Redefining:: Changing a macro's definition.
  255. * Macro Pitfalls:: Macros can confuse the unwary. Here we explain
  256. several common problems and strange features.
  257. 
  258. File: cpp Node: Simple Macros, Prev: Macros, Up: Macros, Next: Argument Macros
  259. Simple Macros
  260. -------------
  261. A "simple macro" is a kind of abbreviation. It is a name which stands
  262. for a fragment of code.
  263. Before you can use a macro, you must "define" it explicitly with the
  264. `#define' command. `#define' is followed by the name of the
  265. macro and then the code it should be an abbreviation for. For example,
  266. #define BUFFER_SIZE 1020
  267. defines a macro named `BUFFER_SIZE' as an abbreviation for the text
  268. `1020'. Therefore, if somewhere after this `#define' command
  269. there comes a C statement of the form
  270. foo = (char *) xmalloc (BUFFER_SIZE);
  271. then the C preprocessor will recognize and "expand" the macro
  272. `BUFFER_SIZE', resulting in
  273. foo = (char *) xmalloc (1020);
  274. the definition must be a single line; however, it may not end in the
  275. middle of a multi-line string constant or character constant.
  276. The use of all upper case for macro names is a standard convention.
  277. Programs are easier to read when it is possible to tell at a glance which
  278. names are macros.
  279. Normally, a macro definition must be a single line, like all C preprocessor
  280. commands. (You can split a long macro definition cosmetically with
  281. Backslash-Newline.) There is one exception: Newlines can be included in
  282. the macro definition if within a string or character constant. By the same
  283. token, it is not possible for a macro definition to contain an unbalanced
  284. quote character; the definition automatically extends to include the
  285. matching quote character that ends the string or character constant.
  286. Comments within a macro definition may contain Newlines, which make no
  287. difference since the comments are entirely replaced with Spaces regardless
  288. of their contents.
  289. Aside from the above, there is no restriction on what can go in a macro
  290. body. Parentheses need not balance. The body need not resemble valid C
  291. code. (Of course, you might get error messages from the C compiler when
  292. you use the macro.)
  293. The C preprocessor scans your program sequentially, so macro definitions
  294. take effect at the place you write them. Therefore, the following input to
  295. the C preprocessor
  296. foo = X;
  297. #define X 4
  298. bar = X;
  299. produces as output
  300. foo = X;
  301. bar = 4;
  302. After the preprocessor expands a macro name, the macro's definition body is
  303. appended to the front of the remaining input, and the check for macro calls
  304. continues. Therefore, the macro body can contain calls to other macros.
  305. For example, after
  306. #define BUFSIZE 1020
  307. #define TABLESIZE BUFSIZE
  308. the name `TABLESIZE' when used in the program would go through two
  309. stages of expansion, resulting ultimately in `1020'.
  310. This is not at all the same as defining `TABLESIZE' to be `1020'.
  311. The `#define' for `TABLESIZE' uses exactly the body you
  312. specify---in this case, `BUFSIZE'---and does not check to see whether
  313. it too is the name of a macro. It's only when you *use* `TABLESIZE'
  314. that the result of its expansion is checked for more macro names.
  315. *Note Cascaded Macros::.
  316. 
  317. File: cpp Node: Argument Macros, Prev: Simple Macros, Up: Macros, Next: Predefined
  318. Macros with Arguments
  319. ---------------------
  320. A simple macro always stands for exactly the same text, each time it is
  321. used. Macros can be more flexible when they accept "arguments".
  322. Arguments are fragments of code that you supply each time the macro is
  323. used. These fragments are included in the expansion of the macro according
  324. to the directions in the macro definition.
  325. To define a macro that uses arguments, you write a `#define' command
  326. with a list of "argument names" in parentheses after the name of the
  327. macro. The argument names may be any valid C identifiers, separated by
  328. commas and optionally whitespace. The open-parenthesis must follow the
  329. macro name immediately, with no space in between.
  330. For example, here is a macro that computes the minimum of two numeric
  331. values:
  332. #define min(X, Y) ((X) < (Y) ? (X) : (Y))
  333. To use a macro that expects arguments, you write the name of the macro
  334. followed by a list of "actual arguments" in parentheses. separated by
  335. commas. The number of actual arguments you give must match the number of
  336. arguments the macro expects. Examples of use of the macro `min'
  337. include `min (1, 2)' and `min (x + 28, *p)'.
  338. The expansion text of the macro depends on the arguments you use.
  339. Each of the argument names of the macro is replaced, throughout the
  340. macro definition, with the corresponding actual argument. Using the
  341. same macro `min' defined above, `min (1, 2)' expands into
  342. ((1) < (2) ? (1) : (2))
  343. where `1' has been substituted for `X' and `2' for `Y'.
  344. Likewise, `min (x + 28, *p)' expands into
  345. ((x + 28) < (*p) ? (x + 28) : (*p))
  346. Parentheses in the actual arguments must balance; a comma within
  347. parentheses does not end an argument. However, there is no requirement for
  348. brackets or braces to balance; thus, if you want to supply `array[x =
  349. y, x + 1]' as an argument, you must write it as `array[(x = y, x +
  350. 1)]', which is equivalent C code.
  351. After the actual arguments are substituted into the macro body, the entire
  352. result is appended to the front of the remaining input, and the check for
  353. macro calls continues. Therefore, the actual arguments can contain calls
  354. to other macros, either with or without arguments, or even to the same
  355. macro. The macro body can also contain calls to other macros. For
  356. example, `min (min (a, b), c)' expands into
  357. ((((a) < (b) ? (a) : (b))) < (c)
  358. ? (((a) < (b) ? (a) : (b)))
  359. : (c))
  360. (Line breaks shown here for clarity would not actually be generated.)
  361. If you use the macro name followed by something other than an
  362. open-parenthesis, it is not a call to the macro, and the preprocessor does
  363. not change what you have written. Therefore, it is possible for the same
  364. name to be a variable or function in your program as well as a macro,
  365. and you can choose in each instance whether to refer to the macro
  366. (if an actual argument list follows) or the variable or function (if
  367. an argument list does not follow).
  368. Such dual use of one name could be confusing and should be avoided
  369. except when the two meanings are effectively synonymous: that is, when the
  370. name is both a macro and a function and the two have similar effects. You
  371. can think of the name simply as as a function; use of the name for purposes
  372. other than calling it (such as, to take the address) will refer to the
  373. function, while calls will expand the macro and generate better but
  374. equivalent code. For example, you can use a function named `min' in
  375. the same source file that defines the macro. If you write `&min' with
  376. no argument list, you refer to the function. If you write `min (x,
  377. bb)', with an argument list, the macro is expanded. If you write
  378. `(min) (a, bb)', where the name `min' is not followed by an
  379. open-parenthesis, the macro is not expanded, so you wind up with a call to
  380. the function `min'.
  381. It is not allowed to define the same name as both a simple macro and
  382. a macro with arguments.
  383. In the definition of a macro with arguments, the list of argument names
  384. must follow the macro name immediately with no space in between. If there
  385. is a space after the macro name, the macro is defined as taking no
  386. arguments, and all the rest of the name is taken to be the expansion.
  387. The reason for this is that it is often useful to define a macro that
  388. takes no arguments and whose definition begins with an identifier in
  389. parentheses. This rule about spaces makes it possible for you to do either
  390. #define FOO(x) - 1 / (x)
  391. which defines `FOO' to take an argument and expand into minus the
  392. reciprocal of that argument, or
  393. #define BAR (x) - 1 / (x)
  394. which defines `BAR' to take no argument and always expand into
  395. `(x) - 1 / (x)'.
  396. 
  397. File: cpp Node: Predefined, Prev: Argument Macros, Up: Macros, Next: Stringification
  398. Predefined Macros
  399. -----------------
  400. Several simple macros are predefined. You can use them without giving
  401. definitions for them. They fall into two classes: standard macros and
  402. system-specific macros.
  403. * Menu:
  404. * Standard Predefined:: Standard predefined macros.
  405. * Nonstandard Predefined:: Nonstandard predefined macros.
  406. 
  407. File: cpp Node: Standard Predefined, Prev: Predefined, Up: Predefined, Next: Nonstandard Predefined
  408. Standard Predefined Macros
  409. ..........................
  410. The standard predefined macros are available with the same meanings on all
  411. operating systems and all kinds of machines. Their names all start and end
  412. with double underscores. Here is a table of them.
  413. `__FILE__'
  414. This macro expands to the name of the current input file, in the form
  415. of a C string constant.
  416. `__LINE__'
  417. This macro expands to the current input line number, in the form of a
  418. decimal integer constant. While we call it a predefined macro, it's
  419. a pretty strange macro, since its "definition" changes with each
  420. new line of source code.
  421. This and `__FILE__' are useful in generating an error message to
  422. report an inconsistency detected by the program; the message can state
  423. the source line at which the inconsistency was detected. For example,
  424. fprintf (stderr, "Internal error: negative string length "
  425. "%d at %s, line %d.",
  426. length, __FILE__, __LINE__);
  427. A `#include' command changes the expansions of `__FILE__'
  428. and `__LINE__' to correspond to the included file. At the end of
  429. that file, when processing resumes on the input file that contained
  430. the `#include' command, the expansions of `__FILE__' and
  431. `__LINE__' revert to the values they had before the
  432. `#include' (but `__LINE__' is then incremented by one as
  433. processing moves to the line after the `#include').
  434. The expansions of both `__FILE__' and `__LINE__' are altered
  435. if a `#line' command is used. *Note Combining Sources::.
  436. `__DATE__'
  437. This macro expands to a string constant that describes the date on
  438. which the preprocessor is being run. The string constant contains
  439. eleven characters and looks like `"Jan 29 1987"' or `"Apr
  440. 1 1905"'.
  441. `__TIME__'
  442. This macro expands to a string constant that describes the time at
  443. which the preprocessor is being run. The string constant contains
  444. eight characters and looks like `"23:59:01"'.
  445. `__STDC__'
  446. This macro expands to the constant 1, to signify that this is ANSI
  447. Standard C. (Whether that is actually true depends on what C compiler
  448. will operate on the output from the preprocessor.)
  449. 
  450. File: cpp Node: Nonstandard Predefined, Prev: Standard Predefined, Up: Predefined
  451. Nonstandard Predefined Macros
  452. .............................
  453. The C preprocessor normally has several predefined macros that vary between
  454. machines because their purpose is to indicate what type of system and
  455. machine is in use. This manual, being for all systems and machines, cannot
  456. tell you exactly what their names are; instead, we offer a list of some
  457. typical ones.
  458. Some nonstandard predefined macros describe the operating system in use,
  459. with more or less specificity. For example,
  460. `unix'
  461. `unix' is normally predefined on all Unix systems.
  462. `BSD'
  463. `BSD' is predefined on recent versions of Berkeley Unix
  464. (perhaps only in version 4.3).
  465. Other nonstandard predefined macros describe the kind of CPU, with more or
  466. less specificity. For example,
  467. `vax'
  468. `vax' is predefined on Vax computers.
  469. `mc68000'
  470. `mc68000' is predefined on most computers whose CPU is a 68000,
  471. 68010 or 68020.
  472. `m68k'
  473. `m68k' is also predefined on most computers whose CPU is a 68000.
  474. 68010 or 68020; however, some makers use `mc68000' and some use
  475. `m68k'. Some predefine both names.
  476. `M68020'
  477. `M68020' has been observed to be predefined on some systems that
  478. use 68020 CPUs---in addition to `mc68000' and `m68k' that
  479. are less specific.
  480. Yet other nonstandard predefined macros describe the manufacturer of
  481. the system. For example,
  482. `sun'
  483. `sun' is predefined on all models of Sun computers.
  484. `pyr'
  485. `sun' is predefined on all models of Pyramid computers.
  486. These predefined symbols are not only nonstandard, they are contrary to the
  487. ANSI standard because their names do not start with underscores. However,
  488. the GNU C preprocessor would be useless if it did not predefine the same
  489. names that are normally predefined on the system and machine you are using.
  490. Even system header files check the predefined names and will generate
  491. incorrect declarations if they do not find the names that are expected.
  492. The set of nonstandard predefined names in the GNU C preprocessor is controlled
  493. by the macro `PREDEFS', which should be set with a `-D' switch
  494. in the `Makefile' to a string constant containing names separated
  495. by commas. The Doublequotes that delimit the string constant must be
  496. escaped with Backslashes to get them through the shell. For example,
  497. `\"unix,sun,m68k,mc68000\"' is used on Suns.
  498. 
  499. File: cpp Node: Stringification, Prev: Predefined, Up: Macros, Next: Concatenation
  500. Stringification
  501. ---------------
  502. "Stringification" means turning an code fragment into a string constant
  503. whose contents are the text for the code fragment. For example,
  504. stringifying `foo (z)' results in `"foo (z)"'.
  505. In the C preprocessor, stringification is an option available when macro
  506. arguments are substituted into the macro definition. In the body of the
  507. definition, when an argument name appears, the character `#' before
  508. the name specifies stringification of the corresponding actual argument
  509. when it is substituted at that point in the definition. The same argument
  510. may be substituted in other places in the definition without
  511. stringification if the argument name appears in those places with no
  512. `#'.
  513. Here is an example of a macro definition that uses stringification:
  514. #define WARN_IF(EXP) \
  515. do { if (EXP) fprintf (stderr, "Warning: " #EXP "\n"); } while (0)
  516. Here the actual argument for `EXP' is substituted once as given,
  517. into the `if' statement, and once as stringified, into the
  518. argument to `fprintf'. The `do' and `while (0)' are
  519. a kludge to make it possible to write `WARN_IF (ARG);',
  520. which the resemblance of `WARN_IF' to a function would make
  521. C programmers want to do; *Note Swallow Semicolon::).
  522. The stringification feature is limited to transforming one macro argument
  523. into one string constant: there is no way to combine the argument with
  524. other text and then stringify it all together. But the example above shows
  525. how an equivalent result can be obtained in ANSI Standard C using the
  526. feature that adjacent string constants are concatenated as one string
  527. constant. The preprocessor stringifies `EXP''s actual argument
  528. into a separate string constant, resulting in text like
  529. do { if (x == 0) fprintf (stderr, "Warning: " "x == 0" "\n"); } while (0)
  530. but the C compiler then sees three consecutive string constants and
  531. concatenates them into one, producing effectively
  532. do { if (x == 0) fprintf (stderr, "Warning: x == 0\n"); } while (0)
  533. Stringification in C involves more than putting doublequote characters
  534. around the fragment; it is necessary to put backslashes in front of all
  535. doublequote characters, and all backslashes in string and character
  536. constants, in order to get a valid C string constant with the proper
  537. contents. Thus, stringifying `p = "foo\n";' results in `"p =
  538. \"foo\\n\";"'. However, backslashes that are not inside of string or
  539. character constants are not duplicated: `\n' by itself stringifies to
  540. `"\n"'.
  541. Whitespace (including comments) in the text being stringified is handled
  542. according to precise rules. All leading and trailing whitespace is ignored.
  543. Any sequence of whitespace in the middle of the text is converted to
  544. a single space in the stringified result.
  545. 
  546. File: cpp Node: Concatenation, Prev: Stringification, Up: Macros, Next: Undefining
  547. Concatenation
  548. -------------
  549. "Concatenation" means joining two strings into one. In the context
  550. of macro expansion, concatenation refers to joining two lexical units
  551. into one longer one. Specifically, an actual argument to the macro can be
  552. concatenated with another actual argument or with fixed text to produce
  553. a longer name. The longer name might be the name of a function,
  554. variable or type, or a C keyword; it might even be the name of another
  555. macro, in which case it will be expanded.
  556. When you define a macro, you request concatenation with the special
  557. operator `##' in the macro body. When the macro is called,
  558. after actual arguments are substituted, all `##' operators are
  559. deleted, and so is any whitespace next to them (including whitespace
  560. that was part of an actual argument). The result is to concatenate
  561. the syntactic tokens on either side of the `##'.
  562. Consider a C program that interprets named commands. There probably needs
  563. to be a table of commands, perhaps an array of structures declared as
  564. follows:
  565. struct command
  566. {
  567. char *name;
  568. void (*function) ();
  569. };
  570. struct command commands[] =
  571. {
  572. { "quit", quit_command},
  573. { "help", help_command},
  574. ...
  575. };
  576. It would be cleaner not to have to give each command name twice, once in
  577. the string constant and once in the function name. A macro which takes the
  578. name of a command as an argument can make this unnecessary. The string
  579. constant can be created with stringification, and the function name by
  580. concatenating the argument with `_command'. Here is how it is done:
  581. #define COMMAND(NAME) { #NAME, NAME ## _command }
  582. struct command commands[] =
  583. {
  584. COMMAND (quit),
  585. COMMAND (help),
  586. ...
  587. };
  588. The usual case of concatenation is concatenating two names (or a name and a
  589. number) into a longer name. But this isn't the only valid case. It is
  590. also possible to concatenate two numbers (or a number and a name, such as
  591. `1.5' and `e3') into a number. Also, multi-character operators
  592. such as `+=' can be formed by concatenation. In some cases it is even
  593. possible to piece together a string constant. However, two pieces of text
  594. that don't together form a valid lexical unit cannot be concatenated. For
  595. example, concatenation with `x' on one side and `+' on the other
  596. is not meaningful because those two characters can't fit together in any
  597. lexical unit of C. The ANSI standard says that such attempts at
  598. concatenation are undefined, but in the GNU C preprocessor it is well
  599. defined: it puts the `x' and `+' side by side with no particular
  600. special results.
  601. Keep in mind that the C preprocessor converts comments to whitespace before
  602. macros are even considered. Therefore, you cannot create a comment by
  603. concatenating `/' and `*': the `/*' sequence that starts a
  604. comment is not a lexical unit, but rather the beginning of a "long" space
  605. character. Also, you can freely use comments next to a `##' in a
  606. macro definition, or in actual arguments that will be concatenated, because
  607. the comments will be converted to spaces at first sight, and concatenation
  608. will later discard the spaces.
  609. 
  610. File: cpp Node: Undefining, Prev: Concatenation, Up: Macros, Next: Redefining
  611. Undefining Macros
  612. -----------------
  613. To "undefine" a macro means to cancel its definition. This is done
  614. with the `#undef' command. `#undef' is followed by the macro
  615. name to be undefined.
  616. Like definition, undefinition occurs at a specific point in the source
  617. file, and it applies starting from that point. The name ceases to be a
  618. macro name, and from that point on it is treated by the preprocessor as if
  619. it had never been a macro name.
  620. For example,
  621. #define FOO 4
  622. x = FOO;
  623. #undef FOO
  624. x = FOO;
  625. expands into
  626. x = 4;
  627. x = FOO;
  628. In this example, `FOO' had better be a variable or function as well
  629. as (temporarily) a macro, in order for the result of the expansion to be
  630. valid C code.
  631. The same form of `#undef' command will cancel definitions with
  632. arguments or definitions that don't expect arguments. The `#undef'
  633. command has no effect when used on a name not currently defined as a macro.
  634. 
  635. File: cpp Node: Redefining, Prev: Undefining, Up: Macros, Next: Macro Pitfalls
  636. Redefining Macros
  637. -----------------
  638. "Redefining" a macro means defining (with `#define') a name that
  639. is already defined as a macro.
  640. A redefinition is trivial if the new definition is transparently identical
  641. to the old one. You probably wouldn't deliberately write a trivial
  642. redefinition, but they can happen automatically when a header file is
  643. included more than once (*Note Header Files::), so they are accepted
  644. silently and without effect.
  645. Nontrivial redefinition is considered likely to be an error, so
  646. it provokes a warning message from the preprocessor. However, sometimes it
  647. is useful to change the definition of a macro in mid-compilation. You can
  648. inhibit the warning by undefining the macro with `#undef' before the
  649. second definition.
  650. In order for a reefinition to be trivial, the new definition must exactly match
  651. the one already in effect, with two possible exceptions:
  652. * Whitespace may be added or deleted at the beginning or the end.
  653. * Whitespace may be changed in the middle (but not inside strings).
  654. However, it may not be eliminated entirely, and it may not be added
  655. where there was no whitespace at all.
  656. Recall that a comment counts as whitespace.
  657. 
  658. File: cpp Node: Macro Pitfalls, Prev: Redefining, Up: Macros
  659. Pitfalls and Subtleties of Macros
  660. ---------------------------------
  661. In this section we describe some special rules that apply to macros and
  662. macro expansion, and point out certain cases in which the rules have
  663. counterintuitive consequences that you must watch out for.
  664. * Menu:
  665. * Misnesting:: Macros can contain unmatched parentheses.
  666. * Macro Parentheses:: Why apparently superfluous parentheses
  667. may be necessary to avoid incorrect grouping.
  668. * Swallow Semicolon:: Macros that look like functions
  669. but expand into compound statements.
  670. * Side Effects:: Unsafe macros that cause trouble when
  671. arguments contain side effects.
  672. * Self-Reference:: Macros whose definitions use the macros' own names.
  673. * Argument Prescan:: Actual arguments are checked for macro calls
  674. before they are substituted.
  675. * Cascaded Macros:: Macros whose definitions use other macros.
  676. 
  677. File: cpp Node: Misnesting, Prev: Macro Pitfalls, Up: Macro Pitfalls, Next: Macro Parentheses
  678. Improperly Nested Constructs
  679. ............................
  680. Recall that when a macro is called with arguments, the arguments are
  681. substituted into the macro body and the result is checked, together with
  682. the rest of the input file, for more macro calls.
  683. It is possible to piece together a macro call coming partially from the
  684. macro body and partially from the actual arguments. For example,
  685. #define double(x) (2*(x))
  686. #define call_with_1(x) x(1)
  687. would expand `call_with_1 (double)' into `(2*(1))'.
  688. Macro definitions do not have to have balanced parentheses. By writing an
  689. unbalanced open parenthesis in a macro body, it is possible to create a
  690. macro call that begins inside the macro body but ends outside of it. For
  691. example,
  692. #define strange(file) fprintf (file, "%s %d",
  693. ...
  694. strange(stderr) p, 35)
  695. This bizarre example expands to `fprintf (stderr, "%s %d", p, 35)'!
  696. 
  697. File: cpp Node: Macro Parentheses, Prev: Misnesting, Up: Macro Pitfalls, Next: Swallow Semicolon
  698. Unintended Grouping of Arithmetic
  699. .................................
  700. You may have noticed that in most of the macro definition examples shown
  701. above, each occurrence of a macro argument name had parentheses around it.
  702. In addition, another pair of parentheses usually surround the entire macro
  703. definition. Here is why it is best to write macros that way.
  704. Suppose you define a macro as follows
  705. #define ceil_div(x, y) (x + y - 1) / y
  706. whose purpose is to divide, rounding up. (One use for this
  707. operation is to compute how many `int''s are needed to hold
  708. a certain number of `char''s.) Then suppose it is used as follows:
  709. a = ceil_div (b & c, sizeof (int));
  710. This expands into
  711. a = (b & c + sizeof (int) - 1) / sizeof (int);
  712. which is does not do what is intended the operator-precedence rules of
  713. C make it equivalent to
  714. a = (b & (c + sizeof (int) - 1)) / sizeof (int);
  715. What we want is
  716. a = ((b & c) + sizeof (int) - 1)) / sizeof (int);
  717. Defining the macro as
  718. #define ceil_div(x, y) ((x) + (y) - 1) / (y)
  719. provides the desired result.
  720. However, unintended grouping can result in another way. Consider
  721. `sizeof ceil_div(1, 2)'. That has the appearance of a C expression
  722. that would compute the size of the type of `ceil_div (1, 2)', but in
  723. fact it means something very different. Here is what it expands to:
  724. sizeof ((1) + (2) - 1) / (2)
  725. This would take the size of an integer and divide it by two. The precedence
  726. rules have put the division outside the `sizeof' when it was intended
  727. to be inside.
  728. Parentheses around the entire macro definition can prevent such problems.
  729. Here, then, is the recommended way to define `ceil_div':
  730. #define ceil_div(x, y) (((x) + (y) - 1) / (y))
  731. 
  732. File: cpp Node: Swallow Semicolon, Prev: Macro Parentheses, Up: Macro Pitfalls, Next: Side Effects
  733. Swallowing the Semicolon
  734. ........................
  735. Often it is desirable to define a macro that expands into a compound
  736. statement. Consider, for example, the following macro, that advances a
  737. pointer (the argument `p' says where to find it) across whitespace
  738. characters:
  739. #define SKIP_SPACES (p, limit) \
  740. { register char *lim = (limit); \
  741. while (p != lim) { \
  742. if (*p++ != ' ') { \
  743. p--; break; }}}
  744. Here Backslash-Newline is used to split the macro definition, which must
  745. be a single line, so that it resembles the way such C code would be
  746. layed out if not part of a macro definition.
  747. A call to this macro might be `SKIP_SPACES (p, lim)'. Strictly
  748. speaking, the call expands to a compound statement, which is a complete
  749. statement with no need for a semicolon to end it. But it looks like a
  750. function call. So it minimizes confusion if you can use it like a function
  751. call, writing a semicolon afterward, as in `SKIP_SPACES (p, lim);'
  752. But this can cause trouble before `else' statements, because the
  753. semicolon is actually a null statement. Suppose you write
  754. if (*p != 0)
  755. SKIP_SPACES (p, lim);
  756. else ...
  757. The presence of two statements---the compound statement and a null
  758. statement---in between the `if' condition and the `else'
  759. makes invalid C code.
  760. The definition of the macro `SKIP_SPACES' can be altered to solve
  761. this problem, using a `do ... while' statement. Here is how:
  762. #define SKIP_SPACES (p, limit) \
  763. do { register char *lim = (limit); \
  764. while (p != lim) { \
  765. if (*p++ != ' ') { \
  766. p--; break; }}} \
  767. while (0)
  768. Now `SKIP_SPACES (p, lim);' expands into
  769. do {...} while (0);
  770. which is one statement.
  771. 
  772. File: cpp Node: Side Effects, Prev: Swallow Semicolon, Up: Macro Pitfalls, Next: Self-Reference
  773. Duplication of Side Effects
  774. ...........................
  775. Let's consider a call to the macro `min':
  776. #define min(X, Y) ((X) < (Y) ? (X) : (Y))
  777. ...
  778. next = min (x + y, foo (z));
  779. expands into
  780. next = ((x + y) < (foo (z)) ? (x + y) : (foo (z)));
  781. where `x + y' has been substituted for `X' and `foo (z)'
  782. for `Y'.
  783. The function `foo' is used only once in the statement as it appears
  784. in the program, but the expression `foo (z)' has been substituted
  785. twice into the macro expansion. As a result, `foo' might be called
  786. two times when the statement is executed. If it has side effects or
  787. if it takes a long time to compute, the results might not be what you
  788. intended. We say that `min' is an "unsafe" macro.
  789. Solving this problem cleanly would involve defining `min' in
  790. a way that would compute the value of `foo (z)' only once.
  791. Unfortunately, the C language offers no way to do this. So the only
  792. solution is to be careful when *using* the macro `min'.
  793. For example, you can calculate the value of `foo (z)', save it
  794. in a variable, and use that variable in `min':
  795. #define min(X, Y) ((X) < (Y) ? (X) : (Y))
  796. ...
  797. {
  798. int tem = foo (z);
  799. next = min (x + y, tem);
  800. }
  801. (where I assume that `foo' returns type `int').
  802. 
  803. File: cpp Node: Self-Reference, Prev: Side Effects, Up: Macro Pitfalls, Next: Argument Prescan
  804. Self-Referential Macros
  805. .......................
  806. A "self-referential" macro is one whose name appears in its definition.
  807. A special feature of ANSI Standard C is that the self-reference is not
  808. considered a macro call. It is passed into the preprocessor output
  809. unchanged.
  810. Let's consider an example:
  811. #define foo (4 + foo)
  812. where `foo' is also a variable in your program.
  813. Following the ordinary rules, each reference to `foo' will expand into
  814. `(4 + foo)'; then this will be rescanned and will expand into `(4
  815. + (4 + foo))'; and so on until it causes a fatal error (memory full) in the
  816. preprocessor.
  817. However, the special rule about self-reference cuts this process short
  818. after one step, at `(4 + foo)'. Therefore, this macro definition
  819. has the possibly useful effect of causing the program to add 4 to
  820. the value of `foo' wherever `foo' is referred to.
  821. In most cases, it is a bad idea to take advantage of this feature.
  822. A person reading the program who sees that `foo' is a variable will
  823. not expect that it is a macro as well. The reader will come across a
  824. the identifier `foo' in the program and think its value should be
  825. that of the variable `foo', whereas in fact the value is four
  826. greater.
  827. The special rule for self-reference applies also to "indirect"
  828. self-reference. This is the case where a macro X expands to use a
  829. macro `y', and `y''s expansion refers to the macro `x'. The
  830. resulting reference to `x' comes indirectly from the expansion of
  831. `x', so it is a self-reference and is not further expanded. Thus,
  832. after
  833. #define x (4 + y)
  834. #define y (2 * x)
  835. `x' would expand into `(4 + (2 * x))'. Clear?
  836. But suppose `y' is used elsewhere, not from the definition of `x'.
  837. Then the use of `x' in the expansion of `y' is not a self-reference
  838. because `x' is not "in progress". So it does expand. However,
  839. the expansion of `x' contains a reference to `y', and that
  840. is an indirect self-reference now because `y' is "in progress".
  841. The result is that `y' expands to `(2 * (4 + y))'.
  842. It is not clear that this behavior would ever be useful, but it is specified
  843. by the ANSI C standard, so you need to understand it.
  844. 
  845. File: cpp Node: Argument Prescan, Prev: Self-Reference, Up: Macro Pitfalls, Next: Cascaded Macros
  846. Separate Expansion of Macro Arguments
  847. .....................................
  848. We have explained that the expansion of a macro, including the substituted
  849. actual arguments, is scanned over again for macro calls to be expanded.
  850. What really happens is more subtle: first each actual argument text is scanned
  851. separately for macro calls. Then the results of this are substituted into
  852. the macro body to produce the macro expansion, and the macro expansion
  853. is scanned again for macros to expand.
  854. The result is that the actual arguments are scanned *twice* to expand
  855. macro calls in them.
  856. Most of the time, this has no effect. If the actual argument contained
  857. any macro calls, they are expanded during the first scan. The result
  858. therefore contains no macro calls, so the second scan does not change it.
  859. If the actual argument were substituted as given, with no prescan,
  860. the single remaining scan would find the same macro calls and produce
  861. the same results.
  862. You might expect the double scan to change the results when a
  863. self-referential macro is used in an actual argument of another macro
  864. (*Note Self-Reference::): the self-referential macro would be expanded once
  865. in the first scan, and a second time in the second scan. But this is not
  866. what happens. The self-references that do not expand in the first scan are
  867. marked so that they will not expand in the second scan either.
  868. The prescan is not done when an argument is stringified or concatenated.
  869. (More precisely, stringification and concatenation use the argument as
  870. written, in un-prescanned form. The same actual argument would be used in
  871. prescanned form if it is substituted elsewhere without stringification or
  872. concatenation.) Thus,
  873. #define str(s) #s
  874. #define foo 4
  875. str (foo)
  876. expands to `"foo"'. Once more, prescan has been prevented from
  877. having any noticeable effect.
  878. You might now ask, "Why mention the prescan, if it makes no difference?
  879. Why not skip it and make the preprocessor faster?" The answer is that the
  880. prescan does make a difference in two special cases:
  881. * Nested calls to a macro.
  882. * Macros that call other macros that stringify or concatenate.
  883. We say that "nested" calls to a macro occur when a macro's actual
  884. argument contains a call to that very macro. For example, if `f'
  885. is a macro that expects one argument, `f (f (1))' is a nested
  886. pair of calls to `f'. The desired expansion is made by
  887. expanding `f (1)' and substituting that into the definition of
  888. `f'. The prescan causes the expected result to happen.
  889. Without the prescan, `f (1)' itself would be substituted as
  890. an actual argument, and the inner use of `f' would appear
  891. during the main scan as an indirect self-reference and would not
  892. be expanded. Here, the prescan cancels an undesirable side effect
  893. (in the medical, not computational, sense of the term) of the special
  894. rule for self-referential macros.
  895. There is also one case where prescan is useful. It is possible
  896. to use prescan to expand an argument and then stringify it---if you use
  897. two levels of macros. Let's add a new macro `xstr' to the
  898. example shown above:
  899. #define xstr(s) str(s)
  900. #define str(s) #s
  901. #define foo 4
  902. xstr (foo)
  903. This expands into `"4"', not `"foo"'. The reason for the
  904. difference is that the argument of `xstr' is expanded at prescan
  905. (because `xstr' does not specify stringification or concatenation of
  906. the argument). The result of prescan then forms the actual argument for
  907. `str'. `str' uses its argument without prescan because it
  908. performs strigification; but it cannot prevent or undo the prescanning
  909. already done by `xstr'.
  910. 
  911. File: cpp Node: Cascaded Macros, Prev: Argument Prescan, Up: Macro Pitfalls
  912. Cascaded Use of Macros
  913. ......................
  914. A "cascade" of macros is when one macro's body contains a reference
  915. to another macro. This is very common practice. For example,
  916. #define BUFSIZE 1020
  917. #define TABLESIZE BUFSIZE
  918. This is not at all the same as defining `TABLESIZE' to be `1020'.
  919. The `#define' for `TABLESIZE' uses exactly the body you
  920. specify---in this case, `BUFSIZE'---and does not check to see whether
  921. it too is the name of a macro.
  922. It's only when you *use* `TABLESIZE' that the result of its expansion
  923. is checked for more macro names.
  924. This makes a difference if you change the definition of `BUFSIZE'
  925. at some point in the source file. `TABLESIZE', defined as shown,
  926. will always expand using the definition of `BUFSIZE' that is
  927. currently in effect:
  928. #define BUFSIZE 1020
  929. #define TABLESIZE BUFSIZE
  930. #undef BUFSIZE
  931. #define BUFSIZE 37
  932. Now `TABLESIZE' expands (in two stages) to `37'.
  933. 
  934. File: cpp Node: Conditionals, Prev: Macros, Up: Top, Next: Combining Sources
  935. Conditionals
  936. ============
  937. In a macro processor, a "conditional" is a command that allows a part
  938. of the program to be ignored during compilation, on some conditions.
  939. In the C preprocessor, a conditional can test either an arithmetic expression
  940. or whether a name is defined as a macro.
  941. A conditional in the C preprocessor resembles in some ways an `if'
  942. statement in C, but it is important to understand the difference between
  943. them. The condition in an `if' statement is tested during the execution
  944. of your program. Its purpose is to allow your program to behave differently
  945. from run to run, depending on the data it is operating on. The condition
  946. in a preprocessor conditional command is tested when your program is compiled.
  947. Its purpose is to allow different code to be included in the program depending
  948. on the situation at the time of compilation.
  949. * Menu:
  950. * Uses: Conditional Uses. What conditionals are for.
  951. * Syntax: Conditional Syntax. How conditionals are written.
  952. * Deletion: Deleted Code. Making code into a comment.
  953. * Macros: Conditionals-Macros. Why conditionals are used with macros.
  954. * Errors: #error Command. Detecting inconsistent compilation parameters.
  955. 
  956. File: cpp Node: Conditional Uses, Prev: Conditionals, Up: Conditionals, Next: Conditional Syntax
  957. Generally there are three kinds of reason to use a conditional.
  958. * A program may need to use different code depending on the machine or
  959. operating system it is to run on. In some cases the code for one
  960. operating system may be erroneous on another operating system; for
  961. example, it might refer to library routines that do not exist on the
  962. other system. When this happens, it is not enough to avoid executing
  963. the invalid code: merely having it in the program makes it impossible
  964. to link the program and run it. With a preprocessor conditional, the
  965. offending code can be effectively excised from the program when it is
  966. not valid.
  967. * You may want to be able to compile the same source file into two
  968. different programs. Sometimes the difference between the programs is
  969. that one makes frequent time-consuming consistency checks on its
  970. intermediate data while the other does not.
  971. * A conditional whose condition is always false is a good way to exclude
  972. code from the program but keep it as a sort of comment for future
  973. reference.
  974. Most simple programs that are intended to run on only one machine will
  975. not need to use preprocessor conditionals.
  976. 
  977. File: cpp Node: Conditional Syntax, Prev: Conditional Uses, Up: Conditionals, Next: Conditionals-Macros
  978. Syntax of Conditionals
  979. ----------------------
  980. A conditional in the C preprocessor begins with a "conditional
  981. command": `#if', `#ifdef' or `#ifndef'.*Note Conditionals::,
  982. for info on `#ifdef' and `#ifndef'; only `#if' is explained
  983. here.
  984. * Menu:
  985. * If: #if Command. Basic conditionals using `#if' and `#endif'.
  986. * Else: #else Command. Including some text if the condition fails.
  987. * Elif: #elif Command. Testing several alternative possibilities.
  988. 
  989. File: cpp Node: #if Command, Prev: Conditional Syntax, Up: Conditional Syntax, Next: #else Command
  990. The `#if' Command
  991. .................
  992. The `#if' command in its simplest form consists of
  993. #if EXPRESSION
  994. CONTROLLED TEXT
  995. #endif /* EXPRESSION */
  996. The comment following the `#endif' is not required, but it is a good
  997. practice because it helps people match the `#endif' to the
  998. corresponding `#if'. Such comments should always be used, except in
  999. short conditionals that are not nested. In fact, you can put anything at
  1000. all after the `#endif' and it will be ignored by the GNU C preprocessor,
  1001. but only comments are acceptable in ANSI Standard C.
  1002. EXPRESSION is a C expression of integer type, subject to stringent
  1003. restrictions. It may contain
  1004. * Integer constants, which are all regarded as `long' or
  1005. `unsigned long'.
  1006. * Character constants, which are interpreted according to the character
  1007. set and conventions of the machine and operating system on which the
  1008. preprocessor is running. The GNU C preprocessor uses the C data type
  1009. `char' for these character constants; therefore, whether some
  1010. character codes are negative is determined by the C compiler used to
  1011. compile the preprocessor. If it treats `char' as signed, then
  1012. character codes large enough to set the sign bit will be considered
  1013. negative; otherwise, no character code is considered negative.
  1014. * Arithmetic operators for addition, subtraction, multiplication,
  1015. division, bitwise operations, shifts, comparisons, and `&&' and
  1016. `||'.
  1017. * Identifiers that are not macros, which are all treated as zero(!).
  1018. * Macro calls. All macro calls in the expression are expanded before
  1019. actual computation of the expression's value begins.
  1020. Note that `sizeof' operators and `enum'-type values are not allowed.
  1021. `enum'-type values, like all other identifiers that are not taken
  1022. as macro calls and expanded, are treated as zero.
  1023. The text inside of a conditional can include preprocessor commands. Then
  1024. the commands inside the conditional are obeyed only if that branch of the
  1025. conditional succeeds. The text can also contain other conditional groups.
  1026. However, the `#if''s and `#endif''s must balance.
  1027. 
  1028. File: cpp Node: #else Command, Prev: #if Command, Up: Conditional Syntax, Next: #elif Command
  1029. The `#else' Command
  1030. ...................
  1031. The `#else' command can be added a conditional to provide alternative
  1032. text to be used if the condition is false. This looks like
  1033. #if EXPRESSION
  1034. TEXT-IF-TRUE
  1035. #else /* Not EXPRESSION */
  1036. TEXT-IF-FALSE
  1037. #endif /* Not EXPRESSION */
  1038. If EXPRESSION is nonzero, and the TEXT-IF-TRUE is considered
  1039. included, then `#else' acts like a failing conditional and the
  1040. TEXT-IF-FALSE is ignored. Contrariwise, if the `#if'
  1041. conditional fails, the TEXT-IF-FALSE is considered included.
  1042. 
  1043. File: cpp Node: #elif Command, Prev: #else Command, Up: Conditional Syntax
  1044. The `#elif' Command
  1045. ...................
  1046. One common case of nested conditionals is used to check for more than two
  1047. possible alternatives. For example, you might have
  1048. #if X == 1
  1049. ...
  1050. #else /* X != 1 */
  1051. #if X == 2
  1052. ...
  1053. #else /* X != 2 */
  1054. ...
  1055. #endif /* X != 2 */
  1056. #endif /* X != 1 */
  1057. Another conditional command, `#elif', allows this to be abbreviated
  1058. as follows:
  1059. #if X == 1
  1060. ...
  1061. #elif X == 2
  1062. ...
  1063. #else /* X != 2 and X != 1*/
  1064. ...
  1065. #endif /* X != 2 and X != 1*/
  1066. `#elif' stands for "else if". Like `#else', it goes in the
  1067. middle of a `#if'-`#endif' pair and subdivides it; it does not
  1068. require a matching `#endif' of its own. Like `#if', the
  1069. `#elif' command includes an expression to be tested.
  1070. The text following the `#elif' is processed only if the original
  1071. `#if'-condition failed and the `#elif' condition succeeeds. More
  1072. than one `#elif' can go in the same `#if'-`#endif' group.
  1073. Then the text after each `#elif' is processed only if the `#elif'
  1074. condition succeeds after the original `#if' and any previous
  1075. `#elif''s within it have failed. `#else' is equivalent to
  1076. `#elif 1', and `#else' is allowed after any number of
  1077. `#elif''s, but `#elif' may not follow a `#else'.
  1078. 
  1079. File: cpp Node: Deleted Code, Prev: Conditional Syntax, Up: Conditionals, Next: Conditionals-Macros
  1080. Keeping Deleted Code for Future Reference
  1081. -----------------------------------------
  1082. If you replace or delete a part of the program but want to keep the old
  1083. code around as a comment for future reference, the easy way to do this is
  1084. to put `#if 0' before it and `#endif' after it.
  1085. This works even if the code being turned off contains conditionals, but
  1086. they must be entire conditionals (balanced `#if' and `#endif').
  1087. 
  1088. File: cpp Node: Conditionals-Macros, Prev: Deleted Code, Up: Conditionals, Next: #error Command
  1089. Conditionals and Macros
  1090. -----------------------
  1091. Conditionals are rarely useful except in connection with macros. A
  1092. `#if' command whose expression uses no macros is equivalent to
  1093. `#if 1' or `#if 0'; you might as well determine which one, by
  1094. computing the value of the expression yourself, and then simplify the
  1095. program. But when the expression uses macros, its value can vary from
  1096. compilation to compilation.
  1097. For example, here is a conditional that tests the expression
  1098. `BUFSIZE == 1020', where `BUFSIZE' must be a macro.
  1099. #if BUFSIZE == 1020
  1100. printf ("Large buffers!\n");
  1101. #endif /* BUFSIZE is large */
  1102. The special operator `defined' may be used in `#if' expressions
  1103. to test whether a certain name is defined as a macro. Either
  1104. `defined NAME' or `defined (NAME)'.
  1105. is an expression whose value is 1 if NAME is defined as macro at
  1106. the current point in the program, and 0 otherwise. For the
  1107. `defined' operator it makes no difference what the definition of
  1108. the macro is; all that matters is whether there is a definition. Thus,
  1109. for example,
  1110. #if defined (vax) || defined (ns16000)
  1111. would include the following code if either of the names `vax' and
  1112. `ns16000' is defined as a macro.
  1113. If a macro is defined and later undefined with `#undef',
  1114. subsequent use of the `defined' operator will return 0, because
  1115. the name is no longer defined. If the macro is defined again with
  1116. another `#define', `defined' will recommence returning 1.
  1117. Conditionals that test just the definedness of one name are very common, so
  1118. there are two special short conditional commands for this case. They are
  1119. `#ifdef NAME'
  1120. is equivalent to `#if defined (NAME)'.
  1121. `#ifndef NAME'
  1122. is equivalent to `#if ! defined (NAME)'.
  1123. Macro definitions can vary between compilations for several reasons.
  1124. * Some macros are predefined on each kind of machine. For example, on a
  1125. Vax, the name `vax' is a predefined macro. On other machines, it
  1126. would not be defined.
  1127. * Many more macros are defined by system header files. Different
  1128. systems and machines define different macros, or give them different
  1129. values. It is useful to test these macros with conditionals to avoid
  1130. using a system feature on a machine where it is not implemented.
  1131. * Macros are a common way of allowing users to customize a program for
  1132. different machines or applications. For example, the macro
  1133. `BUFSIZE' might be defined in a configuration file for your
  1134. program that is included as a header file in each source file. You
  1135. would use `BUFSIZE' in a preprocessor conditional in order to
  1136. generate different code depending on the chosen configuration.
  1137. * Macros can be defined or undefined with `-D' and `-U'
  1138. command switches when you compile the program. You can arrange to
  1139. compile the same source file into two different programs by choosing
  1140. a macro name to specify which program you want, writing conditionals
  1141. to test whether or how this macro is defined, and then controlling
  1142. the state of the macro with compiler command switches.
  1143. *Note Invocation::.
  1144. 
  1145. File: cpp Node: #error Command, Prev: Conditionals-Macros, Up: Conditionals
  1146. The `#error' Command
  1147. --------------------
  1148. The command `#error' causes the preprocessor to report a fatal
  1149. error. The rest of the line that follows `#error' is used as the
  1150. error message.
  1151. You would use `#error' inside of a conditional that detects a
  1152. combination of parameters which you know the program does not properly
  1153. support. For example, if you know that the program will not run
  1154. properly on a Vax, you might write
  1155. #ifdef vax
  1156. #error Won't work on Vaxen. See comments at get_last_object.
  1157. #endif
  1158. *Note Nonstandard Predefined::, for why this works.
  1159. If you have several configuration parameters that must be set up by
  1160. the installation in a consistent way, you can use conditionals to detect
  1161. an inconsistency and report it with `#error'. For example,
  1162. #if HASH_TABLE_SIZE % 2 == 0 || HASH_TABLE_SIZE % 3 == 0 \
  1163. || HASH_TABLE_SIZE % 5 == 0
  1164. #error HASH_TABLE_SIZE should not be divisible by a small prime
  1165. #endif
  1166. 
  1167. File: cpp Node: Combining Sources, Prev: Conditionals, Up: Top, Next: Other Commands
  1168. Combining Source Files
  1169. ======================
  1170. One of the jobs of the C preprocessor is to inform the C compiler of where
  1171. each line of C code came from: which source file and which line number.
  1172. C code can come from multiple source files if you use `#include';
  1173. both `#include' and the use of conditionals and macros can cause
  1174. the line number of a line in the preprocessor output to be different
  1175. from the line's number in the original source file. You will appreciate
  1176. the value of making both the C compiler (in error messages) and symbolic
  1177. debuggers such as GDB use the line numbers in your source file.
  1178. The C preprocessor builds on this feature by offering a command by which
  1179. you can control the feature explicitly. This is useful when a file for
  1180. input to the C preprocessor is the output from another program such as the
  1181. `bison' parser generator, which operates on another file that is the
  1182. true source file. Parts of the output from `bison' are generated from
  1183. scratch, other parts come from a standard parser file. The rest are copied
  1184. nearly verbatim from the source file, but their line numbers in the
  1185. `bison' output are not the same as their original line numbers.
  1186. Naturally you would like compiler error messages and symbolic debuggers to
  1187. know the original source file and line number of each line in the
  1188. `bison' output.
  1189. `bison' arranges this by writing `#line' commands into the output
  1190. file. `#line' is a command that specifies the original line number
  1191. and source file name for subsequent input in the current preprocessor input
  1192. file. `#line' has three variants:
  1193. `#line LINENUM'
  1194. Here LINENUM is a decimal integer constant. This specifies that
  1195. the line number of the following line of input, in its original source file,
  1196. was LINENUM.
  1197. `#line LINENUM FILENAME'
  1198. Here LINENUM is a decimal integer constant and FILENAME
  1199. is a string constant. This specifies that the following line of input
  1200. came originally from source file FILENAME and its line number there
  1201. was LINENUM. Keep in mind that FILENAME is not just a
  1202. file name; it is surrounded by Doublequotes.
  1203. `#line ANYTHING ELSE'
  1204. ANYTHING ELSE is checked for macro calls, which are expanded.
  1205. The result should be a decimal integer constant followed optionally
  1206. by a string constant, as described above.
  1207. `#line' commands alter the results of the `__FILE__' and
  1208. `__LINE__' predefined macros from that point on. *Note Standard Predefined::.
  1209. 
  1210. File: cpp Node: Other Commands, Prev: Combining Sources, Up: Top, Next: Output
  1211. Miscellaneous Preprocessor Commands
  1212. ===================================
  1213. This section describes two additional preprocesor commands. They are
  1214. not very useful, but are mentioned for completeness.
  1215. The "null command" consists of a `#' followed by a Newline, with
  1216. only whitespace (including comments) in between. A null command is
  1217. understood as a preprocessor command but has no effect on the preprocessor
  1218. output. The primary significance of the existence of the null command is
  1219. that an input line consisting of just a `#' will produce no output,
  1220. rather than a line of output containing just a `#'. Supposedly
  1221. some old C programs contain such lines.
  1222. The `#pragma' command is specified in the ANSI standard to have an
  1223. arbitrary implementation-defined effect. In the GNU C preprocessor,
  1224. `#pragma' first attempts to run the game `rogue'; if that fails,
  1225. it tries to run the game `hack'; if that fails, it tries to run
  1226. GNU Emacs displaying the Tower of Hanoi; if that fails, it reports a
  1227. fatal error. In any case, preprocessing does not continue.
  1228. 
  1229. File: cpp Node: Output, Prev: Other Commands, Up: Top, Next: Invocation
  1230. C Preprocessor Output
  1231. =====================
  1232. The output from the C preprocessor looks much like the input, except
  1233. that all preprocessor command lines have been replaced with blank lines
  1234. and all comments with spaces. Whitespace within a line is not altered;
  1235. however, a space is inserted after the expansions of most macro calls.
  1236. Source file name and line number information is conveyed by lines of
  1237. the form
  1238. # LINENUM FILENAME
  1239. which are inserted as needed into the middle of the input (but never within
  1240. a string or character constant). Such a line means that the following line
  1241. originated in file FILENAME at line LINENUM.
  1242. 
  1243. File: cpp Node: Invocation, Prev: Output, Up: Top
  1244. Invoking the C Preprocessor
  1245. ===========================
  1246. Most often when you use the C preprocessor you will not have to invoke it
  1247. explicitly: the C compiler will do so automatically. However, the
  1248. preprocessor is sometimes useful individually.
  1249. The C preprocessor expects two file names as arguments, INFILE and
  1250. OUTFILE. The preprocessor reads INFILE together with any other
  1251. files it specifies with `#include'. All the output generated by the
  1252. combined input files is written in OUTFILE.
  1253. Either INFILE or OUTFILE may be `-', which as INFILE
  1254. means to read from standard input and as OUTFILE means to write to
  1255. standard output. Also, if OUTFILE or both file names are omitted,
  1256. the standard output and standard input are used for the omitted file names.
  1257. Here is a table of command switches accepted by the C preprocessor. Most
  1258. of them can also be given when compiling a C program; they are passed along
  1259. automatically to the preprocessor when it is invoked by the compiler.
  1260. `-P'
  1261. Inhibit generation of `#'-lines with line-number information in
  1262. the output from the preprocessor (*Note Output::). This might be
  1263. useful when running the preprocessor on something that is not C code
  1264. and will be sent to a program which might be confused by the
  1265. `#'-lines
  1266. `-C'
  1267. Do not discard comments: pass them through to the output file.
  1268. Comments appearing in arguments of a macro call will be copied to the
  1269. output before the expansion of the macro call.
  1270. `-T'
  1271. Process ANSI standard trigraph sequences. These are three-character
  1272. sequences, all starting with `??', that are defined by ANSI C to
  1273. stand for single characters. For example, `??/' stands for
  1274. `\', so `'??/n'' is a character constant for Newline.
  1275. Strictly speaking, the GNU C preprocessor does not support all
  1276. programs in ANSI Standard C unless `-T' is used, but you if you
  1277. ever notice the difference it will be with relief.
  1278. You don't want to know any more about trigraphs.
  1279. `-pedantic'
  1280. Issue warnings required by the ANSI C standard in certain cases such
  1281. as when text other than a comment follows `#else' or `#endif'.
  1282. `-I DIRECTORY'
  1283. Add the directory DIRECTORY to the end of the list of
  1284. directories to be searched for user header files (*Note Include Syntax::).
  1285. `-D NAME'
  1286. Predefine NAME as a macro, with definition `1'.
  1287. `-D NAME=DEFINITION'
  1288. Predefine NAME as a macro, with definition DEFINITION.
  1289. There are no restrictions on the contents of DEFINITION, but if
  1290. you are invoking the preprocessor from a shell or shell-like program
  1291. you may need to use the shell's quoting syntax to protect characters
  1292. such as spaces that have a meaning in the shell syntax.
  1293. `-U NAME'
  1294. Do not predefine NAME. If both `-U' and `-D' are
  1295. specified for one name, the `-U' beats the `-D' and the name
  1296. is not predefined.
  1297. `-undef'
  1298. Do not predefine any nonstandard macros.
  1299. `-d'
  1300. Instead of outputting the result of preprocessing, output a list of
  1301. `#define' commands for all the macros defined during the
  1302. execution of the preprocessor.
  1303. `-i FILE'
  1304. Process FILE as input, discarding the resulting output, before
  1305. processing the regular input file. Because the output generated from
  1306. FILE is discarded, the only effect of `-i FILE' is to
  1307. make the macros defined in FILE available for use in the main
  1308. input.
  1309. 
  1310. File: cpp Node: Concept Index, Prev: Invocation, Up: Top, Next: Index
  1311. Concept Index
  1312. *************
  1313. * Menu:
  1314. * cascaded macros: Cascaded Macros.
  1315. * commands: Commands.
  1316. * concatenation: Concatenation.
  1317. * conditionals: Conditionals.
  1318. * header file: Header Files.
  1319. * line control: Combining Sources.
  1320. * macro body uses macro: Cascaded Macros.
  1321. * null command: Other Commands.
  1322. * output format: Output.
  1323. * predefined macros: Predefined.
  1324. * preprocessor commands: Commands.
  1325. * redefining macros: Redefining.
  1326. * self-reference: Self-Reference.
  1327. * semicolons (after macro calls): Swallow Semicolon.
  1328. * side effects (in macro arguments): Side Effects.
  1329. * stringification: Stringification.
  1330. * switches: Invocation.
  1331. * undefining macros: Undefining.
  1332. * unsafe macros: Side Effects.
  1333. 
  1334. File: cpp Node: Index, Prev: Concept Index, Up: Top
  1335. Index of Commands, Macros and Switches
  1336. **************************************
  1337. * Menu:
  1338. * #elif: #elif Command.
  1339. * #else: #else Command.
  1340. * #error: #error Command.
  1341. * #if: Conditional Syntax.
  1342. * #ifdef: Conditionals-Macros.
  1343. * #ifndef: Conditionals-Macros.
  1344. * #include: Include Syntax.
  1345. * #line: Combining Sources.
  1346. * #pragma: Other Commands.
  1347. * -C: Invocation.
  1348. * -D: Invocation.
  1349. * -d: Invocation.
  1350. * -I: Invocation.
  1351. * -i: Invocation.
  1352. * -P: Invocation.
  1353. * -pedantic: Invocation.
  1354. * -T: Invocation.
  1355. * -U: Invocation.
  1356. * -undef: Invocation.
  1357. * BSD: Nonstandard Predefined.
  1358. * defined: Conditionals-Macros.
  1359. * M68020: Nonstandard Predefined.
  1360. * m68k: Nonstandard Predefined.
  1361. * mc68000: Nonstandard Predefined.
  1362. * pyr: Nonstandard Predefined.
  1363. * sun: Nonstandard Predefined.
  1364. * system header files: Header Uses.
  1365. * unix: Nonstandard Predefined.
  1366. * vax: Nonstandard Predefined.
  1367. * __DATE__: Standard Predefined.
  1368. * __FILE__: Standard Predefined.
  1369. * __LINE__: Standard Predefined.
  1370. * __STDC__: Standard Predefined.
  1371. * __TIME__: Standard Predefined.
  1372. 
  1373. Tag table:
  1374. Node: Top737
  1375. Node: Global Actions3284
  1376. Node: Commands5126
  1377. Node: Header Files6717
  1378. Node: Header Uses7047
  1379. Node: Include Syntax8428
  1380. Node: Include Operation11291
  1381. Node: Macros12930
  1382. Node: Simple Macros13832
  1383. Node: Argument Macros16865
  1384. Node: Predefined21575
  1385. Node: Standard Predefined21993
  1386. Node: Nonstandard Predefined24421
  1387. Node: Stringification26910
  1388. Node: Concatenation29738
  1389. Node: Undefining32985
  1390. Node: Redefining33997
  1391. Node: Macro Pitfalls35276
  1392. Node: Misnesting36311
  1393. Node: Macro Parentheses37307
  1394. Node: Swallow Semicolon39133
  1395. Node: Side Effects41014
  1396. Node: Self-Reference42373
  1397. Node: Argument Prescan44606
  1398. Node: Cascaded Macros48306
  1399. Node: Conditionals49318
  1400. Node: Conditional Uses50594
  1401. Node: Conditional Syntax51921
  1402. Node: #if Command52478
  1403. Node: #else Command54730
  1404. Node: #elif Command55363
  1405. Node: Deleted Code56693
  1406. Node: Conditionals-Macros57214
  1407. Node: #error Command60454
  1408. Node: Combining Sources61490
  1409. Node: Other Commands64062
  1410. Node: Output65192
  1411. Node: Invocation65900
  1412. Node: Concept Index69479
  1413. Node: Index70238
  1414. 
  1415. End tag table