home *** CD-ROM | disk | FTP | other *** search
/ Frozen Fish 1: Amiga / FrozenFish-Apr94.iso / bbs / gnu / gcc-2.5.8-bin.lha / info / cpp.info-2 (.txt) < prev    next >
GNU Info File  |  1994-02-21  |  50KB  |  925 lines

  1. This is Info file cpp.info, produced by Makeinfo-1.55 from the input
  2. file cpp.texi.
  3.    This file documents the GNU C Preprocessor.
  4.    Copyright 1987, 1989, 1991, 1992, 1993 Free Software Foundation, Inc.
  5.    Permission is granted to make and distribute verbatim copies of this
  6. manual provided the copyright notice and this permission notice are
  7. preserved on all copies.
  8.    Permission is granted to copy and distribute modified versions of
  9. this manual under the conditions for verbatim copying, provided also
  10. that the entire resulting derived work is distributed under the terms
  11. of a permission notice identical to this one.
  12.    Permission is granted to copy and distribute translations of this
  13. manual into another language, under the above conditions for modified
  14. versions.
  15. File: cpp.info,  Node: Swallow Semicolon,  Next: Side Effects,  Prev: Macro Parentheses,  Up: Macro Pitfalls
  16. Swallowing the Semicolon
  17. ........................
  18.    Often it is desirable to define a macro that expands into a compound
  19. statement.  Consider, for example, the following macro, that advances a
  20. pointer (the argument `p' says where to find it) across whitespace
  21. characters:
  22.      #define SKIP_SPACES (p, limit)  \
  23.      { register char *lim = (limit); \
  24.        while (p != lim) {            \
  25.          if (*p++ != ' ') {          \
  26.            p--; break; }}}
  27. Here Backslash-Newline is used to split the macro definition, which must
  28. be a single line, so that it resembles the way such C code would be
  29. laid out if not part of a macro definition.
  30.    A call to this macro might be `SKIP_SPACES (p, lim)'.  Strictly
  31. speaking, the call expands to a compound statement, which is a complete
  32. statement with no need for a semicolon to end it.  But it looks like a
  33. function call.  So it minimizes confusion if you can use it like a
  34. function call, writing a semicolon afterward, as in `SKIP_SPACES (p,
  35. lim);'
  36.    But this can cause trouble before `else' statements, because the
  37. semicolon is actually a null statement.  Suppose you write
  38.      if (*p != 0)
  39.        SKIP_SPACES (p, lim);
  40.      else ...
  41. The presence of two statements--the compound statement and a null
  42. statement--in between the `if' condition and the `else' makes invalid C
  43. code.
  44.    The definition of the macro `SKIP_SPACES' can be altered to solve
  45. this problem, using a `do ... while' statement.  Here is how:
  46.      #define SKIP_SPACES (p, limit)     \
  47.      do { register char *lim = (limit); \
  48.           while (p != lim) {            \
  49.             if (*p++ != ' ') {          \
  50.               p--; break; }}}           \
  51.      while (0)
  52.    Now `SKIP_SPACES (p, lim);' expands into
  53.      do {...} while (0);
  54. which is one statement.
  55. File: cpp.info,  Node: Side Effects,  Next: Self-Reference,  Prev: Swallow Semicolon,  Up: Macro Pitfalls
  56. Duplication of Side Effects
  57. ...........................
  58.    Many C programs define a macro `min', for "minimum", like this:
  59.      #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
  60.    When you use this macro with an argument containing a side effect,
  61. as shown here,
  62.      next = min (x + y, foo (z));
  63. it expands as follows:
  64.      next = ((x + y) < (foo (z)) ? (x + y) : (foo (z)));
  65. where `x + y' has been substituted for `X' and `foo (z)' for `Y'.
  66.    The function `foo' is used only once in the statement as it appears
  67. in the program, but the expression `foo (z)' has been substituted twice
  68. into the macro expansion.  As a result, `foo' might be called two times
  69. when the statement is executed.  If it has side effects or if it takes
  70. a long time to compute, the results might not be what you intended.  We
  71. say that `min' is an "unsafe" macro.
  72.    The best solution to this problem is to define `min' in a way that
  73. computes the value of `foo (z)' only once.  The C language offers no
  74. standard way to do this, but it can be done with GNU C extensions as
  75. follows:
  76.      #define min(X, Y)                     \
  77.      ({ typeof (X) __x = (X), __y = (Y);   \
  78.         (__x < __y) ? __x : __y; })
  79.    If you do not wish to use GNU C extensions, the only solution is to
  80. be careful when *using* the macro `min'.  For example, you can
  81. calculate the value of `foo (z)', save it in a variable, and use that
  82. variable in `min':
  83.      #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
  84.      ...
  85.      {
  86.        int tem = foo (z);
  87.        next = min (x + y, tem);
  88.      }
  89. (where we assume that `foo' returns type `int').
  90. File: cpp.info,  Node: Self-Reference,  Next: Argument Prescan,  Prev: Side Effects,  Up: Macro Pitfalls
  91. Self-Referential Macros
  92. .......................
  93.    A "self-referential" macro is one whose name appears in its
  94. definition.  A special feature of ANSI Standard C is that the
  95. self-reference is not considered a macro call.  It is passed into the
  96. preprocessor output unchanged.
  97.    Let's consider an example:
  98.      #define foo (4 + foo)
  99. where `foo' is also a variable in your program.
  100.    Following the ordinary rules, each reference to `foo' will expand
  101. into `(4 + foo)'; then this will be rescanned and will expand into `(4
  102. + (4 + foo))'; and so on until it causes a fatal error (memory full) in
  103. the preprocessor.
  104.    However, the special rule about self-reference cuts this process
  105. short after one step, at `(4 + foo)'.  Therefore, this macro definition
  106. has the possibly useful effect of causing the program to add 4 to the
  107. value of `foo' wherever `foo' is referred to.
  108.    In most cases, it is a bad idea to take advantage of this feature.  A
  109. person reading the program who sees that `foo' is a variable will not
  110. expect that it is a macro as well.  The reader will come across the
  111. identifier `foo' in the program and think its value should be that of
  112. the variable `foo', whereas in fact the value is four greater.
  113.    The special rule for self-reference applies also to "indirect"
  114. self-reference.  This is the case where a macro X expands to use a
  115. macro `y', and the expansion of `y' refers to the macro `x'.  The
  116. resulting reference to `x' comes indirectly from the expansion of `x',
  117. so it is a self-reference and is not further expanded.  Thus, after
  118.      #define x (4 + y)
  119.      #define y (2 * x)
  120. `x' would expand into `(4 + (2 * x))'.  Clear?
  121.    But suppose `y' is used elsewhere, not from the definition of `x'.
  122. Then the use of `x' in the expansion of `y' is not a self-reference
  123. because `x' is not "in progress".  So it does expand.  However, the
  124. expansion of `x' contains a reference to `y', and that is an indirect
  125. self-reference now because `y' is "in progress".  The result is that
  126. `y' expands to `(2 * (4 + y))'.
  127.    It is not clear that this behavior would ever be useful, but it is
  128. specified by the ANSI C standard, so you may need to understand it.
  129. File: cpp.info,  Node: Argument Prescan,  Next: Cascaded Macros,  Prev: Self-Reference,  Up: Macro Pitfalls
  130. Separate Expansion of Macro Arguments
  131. .....................................
  132.    We have explained that the expansion of a macro, including the
  133. substituted actual arguments, is scanned over again for macro calls to
  134. be expanded.
  135.    What really happens is more subtle: first each actual argument text
  136. is scanned separately for macro calls.  Then the results of this are
  137. substituted into the macro body to produce the macro expansion, and the
  138. macro expansion is scanned again for macros to expand.
  139.    The result is that the actual arguments are scanned *twice* to expand
  140. macro calls in them.
  141.    Most of the time, this has no effect.  If the actual argument
  142. contained any macro calls, they are expanded during the first scan.
  143. The result therefore contains no macro calls, so the second scan does
  144. not change it.  If the actual argument were substituted as given, with
  145. no prescan, the single remaining scan would find the same macro calls
  146. and produce the same results.
  147.    You might expect the double scan to change the results when a
  148. self-referential macro is used in an actual argument of another macro
  149. (*note Self-Reference::.): the self-referential macro would be expanded
  150. once in the first scan, and a second time in the second scan.  But this
  151. is not what happens.  The self-references that do not expand in the
  152. first scan are marked so that they will not expand in the second scan
  153. either.
  154.    The prescan is not done when an argument is stringified or
  155. concatenated.  Thus,
  156.      #define str(s) #s
  157.      #define foo 4
  158.      str (foo)
  159. expands to `"foo"'.  Once more, prescan has been prevented from having
  160. any noticeable effect.
  161.    More precisely, stringification and concatenation use the argument as
  162. written, in un-prescanned form.  The same actual argument would be used
  163. in prescanned form if it is substituted elsewhere without
  164. stringification or concatenation.
  165.      #define str(s) #s lose(s)
  166.      #define foo 4
  167.      str (foo)
  168.    expands to `"foo" lose(4)'.
  169.    You might now ask, "Why mention the prescan, if it makes no
  170. difference?  And why not skip it and make the preprocessor faster?"
  171. The answer is that the prescan does make a difference in three special
  172. cases:
  173.    * Nested calls to a macro.
  174.    * Macros that call other macros that stringify or concatenate.
  175.    * Macros whose expansions contain unshielded commas.
  176.    We say that "nested" calls to a macro occur when a macro's actual
  177. argument contains a call to that very macro.  For example, if `f' is a
  178. macro that expects one argument, `f (f (1))' is a nested pair of calls
  179. to `f'.  The desired expansion is made by expanding `f (1)' and
  180. substituting that into the definition of `f'.  The prescan causes the
  181. expected result to happen.  Without the prescan, `f (1)' itself would
  182. be substituted as an actual argument, and the inner use of `f' would
  183. appear during the main scan as an indirect self-reference and would not
  184. be expanded.  Here, the prescan cancels an undesirable side effect (in
  185. the medical, not computational, sense of the term) of the special rule
  186. for self-referential macros.
  187.    But prescan causes trouble in certain other cases of nested macro
  188. calls.  Here is an example:
  189.      #define foo  a,b
  190.      #define bar(x) lose(x)
  191.      #define lose(x) (1 + (x))
  192.      
  193.      bar(foo)
  194. We would like `bar(foo)' to turn into `(1 + (foo))', which would then
  195. turn into `(1 + (a,b))'.  But instead, `bar(foo)' expands into
  196. `lose(a,b)', and you get an error because `lose' requires a single
  197. argument.  In this case, the problem is easily solved by the same
  198. parentheses that ought to be used to prevent misnesting of arithmetic
  199. operations:
  200.      #define foo (a,b)
  201.      #define bar(x) lose((x))
  202.    The problem is more serious when the operands of the macro are not
  203. expressions; for example, when they are statements.  Then parentheses
  204. are unacceptable because they would make for invalid C code:
  205.      #define foo { int a, b; ... }
  206. In GNU C you can shield the commas using the `({...})' construct which
  207. turns a compound statement into an expression:
  208.      #define foo ({ int a, b; ... })
  209.    Or you can rewrite the macro definition to avoid such commas:
  210.      #define foo { int a; int b; ... }
  211.    There is also one case where prescan is useful.  It is possible to
  212. use prescan to expand an argument and then stringify it--if you use two
  213. levels of macros.  Let's add a new macro `xstr' to the example shown
  214. above:
  215.      #define xstr(s) str(s)
  216.      #define str(s) #s
  217.      #define foo 4
  218.      xstr (foo)
  219.    This expands into `"4"', not `"foo"'.  The reason for the difference
  220. is that the argument of `xstr' is expanded at prescan (because `xstr'
  221. does not specify stringification or concatenation of the argument).
  222. The result of prescan then forms the actual argument for `str'.  `str'
  223. uses its argument without prescan because it performs stringification;
  224. but it cannot prevent or undo the prescanning already done by `xstr'.
  225. File: cpp.info,  Node: Cascaded Macros,  Next: Newlines in Args,  Prev: Argument Prescan,  Up: Macro Pitfalls
  226. Cascaded Use of Macros
  227. ......................
  228.    A "cascade" of macros is when one macro's body contains a reference
  229. to another macro.  This is very common practice.  For example,
  230.      #define BUFSIZE 1020
  231.      #define TABLESIZE BUFSIZE
  232.    This is not at all the same as defining `TABLESIZE' to be `1020'.
  233. The `#define' for `TABLESIZE' uses exactly the body you specify--in
  234. this case, `BUFSIZE'--and does not check to see whether it too is the
  235. name of a macro.
  236.    It's only when you *use* `TABLESIZE' that the result of its expansion
  237. is checked for more macro names.
  238.    This makes a difference if you change the definition of `BUFSIZE' at
  239. some point in the source file.  `TABLESIZE', defined as shown, will
  240. always expand using the definition of `BUFSIZE' that is currently in
  241. effect:
  242.      #define BUFSIZE 1020
  243.      #define TABLESIZE BUFSIZE
  244.      #undef BUFSIZE
  245.      #define BUFSIZE 37
  246. Now `TABLESIZE' expands (in two stages) to `37'.
  247. File: cpp.info,  Node: Newlines in Args,  Prev: Cascaded Macros,  Up: Macro Pitfalls
  248. Newlines in Macro Arguments
  249. ---------------------------
  250.    Traditional macro processing carries forward all newlines in macro
  251. arguments into the expansion of the macro.  This means that, if some of
  252. the arguments are substituted more than once, or not at all, or out of
  253. order, newlines can be duplicated, lost, or moved around within the
  254. expansion.  If the expansion consists of multiple statements, then the
  255. effect is to distort the line numbers of some of these statements.  The
  256. result can be incorrect line numbers, in error messages or displayed in
  257. a debugger.
  258.    The GNU C preprocessor operating in ANSI C mode adjusts appropriately
  259. for multiple use of an argument--the first use expands all the
  260. newlines, and subsequent uses of the same argument produce no newlines.
  261. But even in this mode, it can produce incorrect line numbering if
  262. arguments are used out of order, or not used at all.
  263.    Here is an example illustrating this problem:
  264.      #define ignore_second_arg(a,b,c) a; c
  265.      
  266.      ignore_second_arg (foo (),
  267.                         ignored (),
  268.                         syntax error);
  269. The syntax error triggered by the tokens `syntax error' results in an
  270. error message citing line four, even though the statement text comes
  271. from line five.
  272. File: cpp.info,  Node: Conditionals,  Next: Combining Sources,  Prev: Macros,  Up: Top
  273. Conditionals
  274. ============
  275.    In a macro processor, a "conditional" is a command that allows a part
  276. of the program to be ignored during compilation, on some conditions.
  277. In the C preprocessor, a conditional can test either an arithmetic
  278. expression or whether a name is defined as a macro.
  279.    A conditional in the C preprocessor resembles in some ways an `if'
  280. statement in C, but it is important to understand the difference between
  281. them.  The condition in an `if' statement is tested during the execution
  282. of your program.  Its purpose is to allow your program to behave
  283. differently from run to run, depending on the data it is operating on.
  284. The condition in a preprocessor conditional command is tested when your
  285. program is compiled.  Its purpose is to allow different code to be
  286. included in the program depending on the situation at the time of
  287. compilation.
  288. * Menu:
  289. * Uses: Conditional Uses.       What conditionals are for.
  290. * Syntax: Conditional Syntax.   How conditionals are written.
  291. * Deletion: Deleted Code.       Making code into a comment.
  292. * Macros: Conditionals-Macros.  Why conditionals are used with macros.
  293. * Assertions::                How and why to use assertions.
  294. * Errors: #error Command.       Detecting inconsistent compilation parameters.
  295. File: cpp.info,  Node: Conditional Uses,  Next: Conditional Syntax,  Up: Conditionals
  296. Why Conditionals are Used
  297. -------------------------
  298.    Generally there are three kinds of reason to use a conditional.
  299.    * A program may need to use different code depending on the machine
  300.      or operating system it is to run on.  In some cases the code for
  301.      one operating system may be erroneous on another operating system;
  302.      for example, it might refer to library routines that do not exist
  303.      on the other system.  When this happens, it is not enough to avoid
  304.      executing the invalid code: merely having it in the program makes
  305.      it impossible to link the program and run it.  With a preprocessor
  306.      conditional, the offending code can be effectively excised from
  307.      the program when it is not valid.
  308.    * You may want to be able to compile the same source file into two
  309.      different programs.  Sometimes the difference between the programs
  310.      is that one makes frequent time-consuming consistency checks on its
  311.      intermediate data while the other does not.
  312.    * A conditional whose condition is always false is a good way to
  313.      exclude code from the program but keep it as a sort of comment for
  314.      future reference.
  315.    Most simple programs that are intended to run on only one machine
  316. will not need to use preprocessor conditionals.
  317. File: cpp.info,  Node: Conditional Syntax,  Next: Deleted Code,  Prev: Conditional Uses,  Up: Conditionals
  318. Syntax of Conditionals
  319. ----------------------
  320.    A conditional in the C preprocessor begins with a "conditional
  321. command": `#if', `#ifdef' or `#ifndef'.  *Note Conditionals-Macros::,
  322. for information on `#ifdef' and `#ifndef'; only `#if' is explained here.
  323. * Menu:
  324. * If: #if Command.     Basic conditionals using `#if' and `#endif'.
  325. * Else: #else Command. Including some text if the condition fails.
  326. * Elif: #elif Command. Testing several alternative possibilities.
  327. File: cpp.info,  Node: #if Command,  Next: #else Command,  Up: Conditional Syntax
  328. The `#if' Command
  329. .................
  330.    The `#if' command in its simplest form consists of
  331.      #if EXPRESSION
  332.      CONTROLLED TEXT
  333.      #endif /* EXPRESSION */
  334.    The comment following the `#endif' is not required, but it is a good
  335. practice because it helps people match the `#endif' to the
  336. corresponding `#if'.  Such comments should always be used, except in
  337. short conditionals that are not nested.  In fact, you can put anything
  338. at all after the `#endif' and it will be ignored by the GNU C
  339. preprocessor, but only comments are acceptable in ANSI Standard C.
  340.    EXPRESSION is a C expression of integer type, subject to stringent
  341. restrictions.  It may contain
  342.    * Integer constants, which are all regarded as `long' or `unsigned
  343.      long'.
  344.    * Character constants, which are interpreted according to the
  345.      character set and conventions of the machine and operating system
  346.      on which the preprocessor is running.  The GNU C preprocessor uses
  347.      the C data type `char' for these character constants; therefore,
  348.      whether some character codes are negative is determined by the C
  349.      compiler used to compile the preprocessor.  If it treats `char' as
  350.      signed, then character codes large enough to set the sign bit will
  351.      be considered negative; otherwise, no character code is considered
  352.      negative.
  353.    * Arithmetic operators for addition, subtraction, multiplication,
  354.      division, bitwise operations, shifts, comparisons, and `&&' and
  355.      `||'.
  356.    * Identifiers that are not macros, which are all treated as zero(!).
  357.    * Macro calls.  All macro calls in the expression are expanded before
  358.      actual computation of the expression's value begins.
  359.    Note that `sizeof' operators and `enum'-type values are not allowed.
  360. `enum'-type values, like all other identifiers that are not taken as
  361. macro calls and expanded, are treated as zero.
  362.    The CONTROLLED TEXT inside of a conditional can include preprocessor
  363. commands.  Then the commands inside the conditional are obeyed only if
  364. that branch of the conditional succeeds.  The text can also contain
  365. other conditional groups.  However, the `#if' and `#endif' commands
  366. must balance.
  367. File: cpp.info,  Node: #else Command,  Next: #elif Command,  Prev: #if Command,  Up: Conditional Syntax
  368. The `#else' Command
  369. ...................
  370.    The `#else' command can be added to a conditional to provide
  371. alternative text to be used if the condition is false.  This is what it
  372. looks like:
  373.      #if EXPRESSION
  374.      TEXT-IF-TRUE
  375.      #else /* Not EXPRESSION */
  376.      TEXT-IF-FALSE
  377.      #endif /* Not EXPRESSION */
  378.    If EXPRESSION is nonzero, and thus the TEXT-IF-TRUE is active, then
  379. `#else' acts like a failing conditional and the TEXT-IF-FALSE is
  380. ignored.  Contrariwise, if the `#if' conditional fails, the
  381. TEXT-IF-FALSE is considered included.
  382. File: cpp.info,  Node: #elif Command,  Prev: #else Command,  Up: Conditional Syntax
  383. The `#elif' Command
  384. ...................
  385.    One common case of nested conditionals is used to check for more
  386. than two possible alternatives.  For example, you might have
  387.      #if X == 1
  388.      ...
  389.      #else /* X != 1 */
  390.      #if X == 2
  391.      ...
  392.      #else /* X != 2 */
  393.      ...
  394.      #endif /* X != 2 */
  395.      #endif /* X != 1 */
  396.    Another conditional command, `#elif', allows this to be abbreviated
  397. as follows:
  398.      #if X == 1
  399.      ...
  400.      #elif X == 2
  401.      ...
  402.      #else /* X != 2 and X != 1*/
  403.      ...
  404.      #endif /* X != 2 and X != 1*/
  405.    `#elif' stands for "else if".  Like `#else', it goes in the middle
  406. of a `#if'-`#endif' pair and subdivides it; it does not require a
  407. matching `#endif' of its own.  Like `#if', the `#elif' command includes
  408. an expression to be tested.
  409.    The text following the `#elif' is processed only if the original
  410. `#if'-condition failed and the `#elif' condition succeeds.  More than
  411. one `#elif' can go in the same `#if'-`#endif' group.  Then the text
  412. after each `#elif' is processed only if the `#elif' condition succeeds
  413. after the original `#if' and any previous `#elif' commands within it
  414. have failed.  `#else' is equivalent to `#elif 1', and `#else' is
  415. allowed after any number of `#elif' commands, but `#elif' may not follow
  416. `#else'.
  417. File: cpp.info,  Node: Deleted Code,  Next: Conditionals-Macros,  Prev: Conditional Syntax,  Up: Conditionals
  418. Keeping Deleted Code for Future Reference
  419. -----------------------------------------
  420.    If you replace or delete a part of the program but want to keep the
  421. old code around as a comment for future reference, the easy way to do
  422. this is to put `#if 0' before it and `#endif' after it.
  423.    This works even if the code being turned off contains conditionals,
  424. but they must be entire conditionals (balanced `#if' and `#endif').
  425. File: cpp.info,  Node: Conditionals-Macros,  Next: Assertions,  Prev: Deleted Code,  Up: Conditionals
  426. Conditionals and Macros
  427. -----------------------
  428.    Conditionals are useful in connection with macros or assertions,
  429. because those are the only ways that an expression's value can vary
  430. from one compilation to another.  A `#if' command whose expression uses
  431. no macros or assertions is equivalent to `#if 1' or `#if 0'; you might
  432. as well determine which one, by computing the value of the expression
  433. yourself, and then simplify the program.
  434.    For example, here is a conditional that tests the expression
  435. `BUFSIZE == 1020', where `BUFSIZE' must be a macro.
  436.      #if BUFSIZE == 1020
  437.        printf ("Large buffers!\n");
  438.      #endif /* BUFSIZE is large */
  439.    (Programmers often wish they could test the size of a variable or
  440. data type in `#if', but this does not work.  The preprocessor does not
  441. understand `sizeof', or typedef names, or even the type keywords such
  442. as `int'.)
  443.    The special operator `defined' is used in `#if' expressions to test
  444. whether a certain name is defined as a macro.  Either `defined NAME' or
  445. `defined (NAME)' is an expression whose value is 1 if NAME is defined
  446. as macro at the current point in the program, and 0 otherwise.  For the
  447. `defined' operator it makes no difference what the definition of the
  448. macro is; all that matters is whether there is a definition.  Thus, for
  449. example,
  450.      #if defined (vax) || defined (ns16000)
  451. would include the following code if either of the names `vax' and
  452. `ns16000' is defined as a macro.  You can test the same condition using
  453. assertions (*note Assertions::.), like this:
  454.      #if #cpu (vax) || #cpu (ns16000)
  455.    If a macro is defined and later undefined with `#undef', subsequent
  456. use of the `defined' operator returns 0, because the name is no longer
  457. defined.  If the macro is defined again with another `#define',
  458. `defined' will recommence returning 1.
  459.    Conditionals that test just the definedness of one name are very
  460. common, so there are two special short conditional commands for this
  461. case.
  462. `#ifdef NAME'
  463.      is equivalent to `#if defined (NAME)'.
  464. `#ifndef NAME'
  465.      is equivalent to `#if ! defined (NAME)'.
  466.    Macro definitions can vary between compilations for several reasons.
  467.    * Some macros are predefined on each kind of machine.  For example,
  468.      on a Vax, the name `vax' is a predefined macro.  On other
  469.      machines, it would not be defined.
  470.    * Many more macros are defined by system header files.  Different
  471.      systems and machines define different macros, or give them
  472.      different values.  It is useful to test these macros with
  473.      conditionals to avoid using a system feature on a machine where it
  474.      is not implemented.
  475.    * Macros are a common way of allowing users to customize a program
  476.      for different machines or applications.  For example, the macro
  477.      `BUFSIZE' might be defined in a configuration file for your
  478.      program that is included as a header file in each source file.  You
  479.      would use `BUFSIZE' in a preprocessor conditional in order to
  480.      generate different code depending on the chosen configuration.
  481.    * Macros can be defined or undefined with `-D' and `-U' command
  482.      options when you compile the program.  You can arrange to compile
  483.      the same source file into two different programs by choosing a
  484.      macro name to specify which program you want, writing conditionals
  485.      to test whether or how this macro is defined, and then controlling
  486.      the state of the macro with compiler command options.  *Note
  487.      Invocation::.
  488.    Assertions are usually predefined, but can be defined with
  489. preprocessor commands or command-line options.
  490. File: cpp.info,  Node: Assertions,  Next: #error Command,  Prev: Conditionals-Macros,  Up: Conditionals
  491. Assertions
  492. ----------
  493.    "Assertions" are a more systematic alternative to macros in writing
  494. conditionals to test what sort of computer or system the compiled
  495. program will run on.  Assertions are usually predefined, but you can
  496. define them with preprocessor commands or command-line options.
  497.    The macros traditionally used to describe the type of target are not
  498. classified in any way according to which question they answer; they may
  499. indicate a hardware architecture, a particular hardware model, an
  500. operating system, a particular version of an operating system, or
  501. specific configuration options.  These are jumbled together in a single
  502. namespace.  In contrast, each assertion consists of a named question and
  503. an answer.  The question is usually called the "predicate".  An
  504. assertion looks like this:
  505.      #PREDICATE (ANSWER)
  506. You must use a properly formed identifier for PREDICATE.  The value of
  507. ANSWER can be any sequence of words; all characters are significant
  508. except for leading and trailing whitespace, and differences in internal
  509. whitespace sequences are ignored.  Thus, `x + y' is different from
  510. `x+y' but equivalent to `x + y'.  `)' is not allowed in an answer.
  511.    Here is a conditional to test whether the answer ANSWER is asserted
  512. for the predicate PREDICATE:
  513.      #if #PREDICATE (ANSWER)
  514. There may be more than one answer asserted for a given predicate.  If
  515. you omit the answer, you can test whether *any* answer is asserted for
  516. PREDICATE:
  517.      #if #PREDICATE
  518.    Most of the time, the assertions you test will be predefined
  519. assertions.  GNU C provides three predefined predicates: `system',
  520. `cpu', and `machine'.  `system' is for assertions about the type of
  521. software, `cpu' describes the type of computer architecture, and
  522. `machine' gives more information about the computer.  For example, on a
  523. GNU system, the following assertions would be true:
  524.      #system (gnu)
  525.      #system (mach)
  526.      #system (mach 3)
  527.      #system (mach 3.SUBVERSION)
  528.      #system (hurd)
  529.      #system (hurd VERSION)
  530. and perhaps others.  The alternatives with more or less version
  531. information let you ask more or less detailed questions about the type
  532. of system software.
  533.    On a Unix system, you would find `#system (unix)' and perhaps one of:
  534. `#system (aix)', `#system (bsd)', `#system (hpux)', `#system (lynx)',
  535. `#system (mach)', `#system (posix)', `#system (svr3)', `#system
  536. (svr4)', or `#system (xpg4)' with possible version numbers following.
  537.    Other values for `system' are `#system (mvs)' and `#system (vms)'.
  538.    *Portability note:* Many Unix C compilers provide only one answer
  539. for the `system' assertion: `#system (unix)', if they support
  540. assertions at all.  This is less than useful.
  541.    An assertion with a multi-word answer is completely different from
  542. several assertions with individual single-word answers.  For example,
  543. the presence of `system (mach 3.0)' does not mean that `system (3.0)'
  544. is true.  It also does not directly imply `system (mach)', but in GNU
  545. C, that last will normally be asserted as well.
  546.    The current list of possible assertion values for `cpu' is: `#cpu
  547. (a29k)', `#cpu (alpha)', `#cpu (arm)', `#cpu (clipper)', `#cpu
  548. (convex)', `#cpu (elxsi)', `#cpu (tron)', `#cpu (h8300)', `#cpu
  549. (i370)', `#cpu (i386)', `#cpu (i860)', `#cpu (i960)', `#cpu (m68k)',
  550. `#cpu (m88k)', `#cpu (mips)', `#cpu (ns32k)', `#cpu (hppa)', `#cpu
  551. (pyr)', `#cpu (ibm032)', `#cpu (rs6000)', `#cpu (sh)', `#cpu (sparc)',
  552. `#cpu (spur)', `#cpu (tahoe)', `#cpu (vax)', `#cpu (we32000)'.
  553.    You can create assertions within a C program using `#assert', like
  554. this:
  555.      #assert PREDICATE (ANSWER)
  556. (Note the absence of a `#' before PREDICATE.)
  557.    Each time you do this, you assert a new true answer for PREDICATE.
  558. Asserting one answer does not invalidate previously asserted answers;
  559. they all remain true.  The only way to remove an assertion is with
  560. `#unassert'.  `#unassert' has the same syntax as `#assert'.  You can
  561. also remove all assertions about PREDICATE like this:
  562.      #unassert PREDICATE
  563.    You can also add or cancel assertions using command options when you
  564. run `gcc' or `cpp'.  *Note Invocation::.
  565. File: cpp.info,  Node: #error Command,  Prev: Assertions,  Up: Conditionals
  566. The `#error' and `#warning' Commands
  567. ------------------------------------
  568.    The command `#error' causes the preprocessor to report a fatal
  569. error.  The rest of the line that follows `#error' is used as the error
  570. message.
  571.    You would use `#error' inside of a conditional that detects a
  572. combination of parameters which you know the program does not properly
  573. support.  For example, if you know that the program will not run
  574. properly on a Vax, you might write
  575.      #ifdef vax
  576.      #error Won't work on Vaxen.  See comments at get_last_object.
  577.      #endif
  578. *Note Nonstandard Predefined::, for why this works.
  579.    If you have several configuration parameters that must be set up by
  580. the installation in a consistent way, you can use conditionals to detect
  581. an inconsistency and report it with `#error'.  For example,
  582.      #if HASH_TABLE_SIZE % 2 == 0 || HASH_TABLE_SIZE % 3 == 0 \
  583.          || HASH_TABLE_SIZE % 5 == 0
  584.      #error HASH_TABLE_SIZE should not be divisible by a small prime
  585.      #endif
  586.    The command `#warning' is like the command `#error', but causes the
  587. preprocessor to issue a warning and continue preprocessing.  The rest of
  588. the line that follows `#warning' is used as the warning message.
  589.    You might use `#warning' in obsolete header files, with a message
  590. directing the user to the header file which should be used instead.
  591. File: cpp.info,  Node: Combining Sources,  Next: Other Commands,  Prev: Conditionals,  Up: Top
  592. Combining Source Files
  593. ======================
  594.    One of the jobs of the C preprocessor is to inform the C compiler of
  595. where each line of C code came from: which source file and which line
  596. number.
  597.    C code can come from multiple source files if you use `#include';
  598. both `#include' and the use of conditionals and macros can cause the
  599. line number of a line in the preprocessor output to be different from
  600. the line's number in the original source file.  You will appreciate the
  601. value of making both the C compiler (in error messages) and symbolic
  602. debuggers such as GDB use the line numbers in your source file.
  603.    The C preprocessor builds on this feature by offering a command by
  604. which you can control the feature explicitly.  This is useful when a
  605. file for input to the C preprocessor is the output from another program
  606. such as the `bison' parser generator, which operates on another file
  607. that is the true source file.  Parts of the output from `bison' are
  608. generated from scratch, other parts come from a standard parser file.
  609. The rest are copied nearly verbatim from the source file, but their
  610. line numbers in the `bison' output are not the same as their original
  611. line numbers.  Naturally you would like compiler error messages and
  612. symbolic debuggers to know the original source file and line number of
  613. each line in the `bison' input.
  614.    `bison' arranges this by writing `#line' commands into the output
  615. file.  `#line' is a command that specifies the original line number and
  616. source file name for subsequent input in the current preprocessor input
  617. file.  `#line' has three variants:
  618. `#line LINENUM'
  619.      Here LINENUM is a decimal integer constant.  This specifies that
  620.      the line number of the following line of input, in its original
  621.      source file, was LINENUM.
  622. `#line LINENUM FILENAME'
  623.      Here LINENUM is a decimal integer constant and FILENAME is a
  624.      string constant.  This specifies that the following line of input
  625.      came originally from source file FILENAME and its line number there
  626.      was LINENUM.  Keep in mind that FILENAME is not just a file name;
  627.      it is surrounded by doublequote characters so that it looks like a
  628.      string constant.
  629. `#line ANYTHING ELSE'
  630.      ANYTHING ELSE is checked for macro calls, which are expanded.  The
  631.      result should be a decimal integer constant followed optionally by
  632.      a string constant, as described above.
  633.    `#line' commands alter the results of the `__FILE__' and `__LINE__'
  634. predefined macros from that point on.  *Note Standard Predefined::.
  635.    The output of the preprocessor (which is the input for the rest of
  636. the compiler) contains commands that look much like `#line' commands.
  637. They start with just `#' instead of `#line', but this is followed by a
  638. line number and file name as in `#line'.  *Note Output::.
  639. File: cpp.info,  Node: Other Commands,  Next: Output,  Prev: Combining Sources,  Up: Top
  640. Miscellaneous Preprocessor Commands
  641. ===================================
  642.    This section describes three additional preprocessor commands.  They
  643. are not very useful, but are mentioned for completeness.
  644.    The "null command" consists of a `#' followed by a Newline, with
  645. only whitespace (including comments) in between.  A null command is
  646. understood as a preprocessor command but has no effect on the
  647. preprocessor output.  The primary significance of the existence of the
  648. null command is that an input line consisting of just a `#' will
  649. produce no output, rather than a line of output containing just a `#'.
  650. Supposedly some old C programs contain such lines.
  651.    The ANSI standard specifies that the `#pragma' command has an
  652. arbitrary, implementation-defined effect.  In the GNU C preprocessor,
  653. `#pragma' commands are not used, except for `#pragma once' (*note
  654. Once-Only::.).  However, they are left in the preprocessor output, so
  655. they are available to the compilation pass.
  656.    The `#ident' command is supported for compatibility with certain
  657. other systems.  It is followed by a line of text.  On some systems, the
  658. text is copied into a special place in the object file; on most systems,
  659. the text is ignored and this command has no effect.  Typically `#ident'
  660. is only used in header files supplied with those systems where it is
  661. meaningful.
  662. File: cpp.info,  Node: Output,  Next: Invocation,  Prev: Other Commands,  Up: Top
  663. C Preprocessor Output
  664. =====================
  665.    The output from the C preprocessor looks much like the input, except
  666. that all preprocessor command lines have been replaced with blank lines
  667. and all comments with spaces.  Whitespace within a line is not altered;
  668. however, a space is inserted after the expansions of most macro calls.
  669.    Source file name and line number information is conveyed by lines of
  670. the form
  671.      # LINENUM FILENAME FLAGS
  672. which are inserted as needed into the middle of the input (but never
  673. within a string or character constant).  Such a line means that the
  674. following line originated in file FILENAME at line LINENUM.
  675.    After the file name comes zero or more flags, which are `1', `2' or
  676. `3'.  If there are multiple flags, spaces separate them.  Here is what
  677. the flags mean:
  678.      This indicates the start of a new file.
  679.      This indicates returning to a file (after having included another
  680.      file).
  681.      This indicates that the following text comes from a system header
  682.      file, so certain warnings should be suppressed.
  683. File: cpp.info,  Node: Invocation,  Next: Concept Index,  Prev: Output,  Up: Top
  684. Invoking the C Preprocessor
  685. ===========================
  686.    Most often when you use the C preprocessor you will not have to
  687. invoke it explicitly: the C compiler will do so automatically.
  688. However, the preprocessor is sometimes useful individually.
  689.    The C preprocessor expects two file names as arguments, INFILE and
  690. OUTFILE.  The preprocessor reads INFILE together with any other files
  691. it specifies with `#include'.  All the output generated by the combined
  692. input files is written in OUTFILE.
  693.    Either INFILE or OUTFILE may be `-', which as INFILE means to read
  694. from standard input and as OUTFILE means to write to standard output.
  695. Also, if OUTFILE or both file names are omitted, the standard output
  696. and standard input are used for the omitted file names.
  697.    Here is a table of command options accepted by the C preprocessor.
  698. These options can also be given when compiling a C program; they are
  699. passed along automatically to the preprocessor when it is invoked by the
  700. compiler.
  701.      Inhibit generation of `#'-lines with line-number information in
  702.      the output from the preprocessor (*note Output::.).  This might be
  703.      useful when running the preprocessor on something that is not C
  704.      code and will be sent to a program which might be confused by the
  705.      `#'-lines.
  706.      Do not discard comments: pass them through to the output file.
  707.      Comments appearing in arguments of a macro call will be copied to
  708.      the output before the expansion of the macro call.
  709. `-traditional'
  710.      Try to imitate the behavior of old-fashioned C, as opposed to ANSI
  711.      C.
  712.         * Traditional macro expansion pays no attention to singlequote
  713.           or doublequote characters; macro argument symbols are
  714.           replaced by the argument values even when they appear within
  715.           apparent string or character constants.
  716.         * Traditionally, it is permissible for a macro expansion to end
  717.           in the middle of a string or character constant.  The
  718.           constant continues into the text surrounding the macro call.
  719.         * However, traditionally the end of the line terminates a
  720.           string or character constant, with no error.
  721.         * In traditional C, a comment is equivalent to no text at all.
  722.           (In ANSI C, a comment counts as whitespace.)
  723.         * Traditional C does not have the concept of a "preprocessing
  724.           number".  It considers `1.0e+4' to be three tokens: `1.0e',
  725.           `+', and `4'.
  726.         * A macro is not suppressed within its own definition, in
  727.           traditional C.  Thus, any macro that is used recursively
  728.           inevitably causes an error.
  729.         * The character `#' has no special meaning within a macro
  730.           definition in traditional C.
  731.         * In traditional C, the text at the end of a macro expansion
  732.           can run together with the text after the macro call, to
  733.           produce a single token.  (This is impossible in ANSI C.)
  734.         * Traditionally, `\' inside a macro argument suppresses the
  735.           syntactic significance of the following character.
  736. `-trigraphs'
  737.      Process ANSI standard trigraph sequences.  These are
  738.      three-character sequences, all starting with `??', that are
  739.      defined by ANSI C to stand for single characters.  For example,
  740.      `??/' stands for `\', so `'??/n'' is a character constant for a
  741.      newline.  Strictly speaking, the GNU C preprocessor does not
  742.      support all programs in ANSI Standard C unless `-trigraphs' is
  743.      used, but if you ever notice the difference it will be with relief.
  744.      You don't want to know any more about trigraphs.
  745. `-pedantic'
  746.      Issue warnings required by the ANSI C standard in certain cases
  747.      such as when text other than a comment follows `#else' or `#endif'.
  748. `-pedantic-errors'
  749.      Like `-pedantic', except that errors are produced rather than
  750.      warnings.
  751. `-Wtrigraphs'
  752.      Warn if any trigraphs are encountered (assuming they are enabled).
  753. `-Wcomment'
  754.      Warn whenever a comment-start sequence `/*' appears in a comment.
  755. `-Wall'
  756.      Requests both `-Wtrigraphs' and `-Wcomment' (but not
  757.      `-Wtraditional').
  758. `-Wtraditional'
  759.      Warn about certain constructs that behave differently in
  760.      traditional and ANSI C.
  761. `-I DIRECTORY'
  762.      Add the directory DIRECTORY to the end of the list of directories
  763.      to be searched for header files (*note Include Syntax::.).  This
  764.      can be used to override a system header file, substituting your
  765.      own version, since these directories are searched before the system
  766.      header file directories.  If you use more than one `-I' option,
  767.      the directories are scanned in left-to-right order; the standard
  768.      system directories come after.
  769. `-I-'
  770.      Any directories specified with `-I' options before the `-I-'
  771.      option are searched only for the case of `#include "FILE"'; they
  772.      are not searched for `#include <FILE>'.
  773.      If additional directories are specified with `-I' options after
  774.      the `-I-', these directories are searched for all `#include'
  775.      commands.
  776.      In addition, the `-I-' option inhibits the use of the current
  777.      directory as the first search directory for `#include "FILE"'.
  778.      Therefore, the current directory is searched only if it is
  779.      requested explicitly with `-I.'.  Specifying both `-I-' and `-I.'
  780.      allows you to control precisely which directories are searched
  781.      before the current one and which are searched after.
  782. `-nostdinc'
  783.      Do not search the standard system directories for header files.
  784.      Only the directories you have specified with `-I' options (and the
  785.      current directory, if appropriate) are searched.
  786. `-nostdinc++'
  787.      Do not search for header files in the C++-specific standard
  788.      directories, but do still search the other standard directories.
  789.      (This option is used when building libg++.)
  790. `-D NAME'
  791.      Predefine NAME as a macro, with definition `1'.
  792. `-D NAME=DEFINITION'
  793.      Predefine NAME as a macro, with definition DEFINITION.  There are
  794.      no restrictions on the contents of DEFINITION, but if you are
  795.      invoking the preprocessor from a shell or shell-like program you
  796.      may need to use the shell's quoting syntax to protect characters
  797.      such as spaces that have a meaning in the shell syntax.  If you
  798.      use more than one `-D' for the same NAME, the rightmost definition
  799.      takes effect.
  800. `-U NAME'
  801.      Do not predefine NAME.  If both `-U' and `-D' are specified for
  802.      one name, the `-U' beats the `-D' and the name is not predefined.
  803. `-undef'
  804.      Do not predefine any nonstandard macros.
  805. `-A PREDICATE(ANSWER)'
  806.      Make an assertion with the predicate PREDICATE and answer ANSWER.
  807.      *Note Assertions::.
  808.      You can use `-A-' to disable all predefined assertions; it also
  809.      undefines all predefined macros that identify the type of target
  810.      system.
  811. `-dM'
  812.      Instead of outputting the result of preprocessing, output a list of
  813.      `#define' commands for all the macros defined during the execution
  814.      of the preprocessor, including predefined macros.  This gives you
  815.      a way of finding out what is predefined in your version of the
  816.      preprocessor; assuming you have no file `foo.h', the command
  817.           touch foo.h; cpp -dM foo.h
  818.      will show the values of any predefined macros.
  819. `-dD'
  820.      Like `-dM' except in two respects: it does *not* include the
  821.      predefined macros, and it outputs *both* the `#define' commands
  822.      and the result of preprocessing.  Both kinds of output go to the
  823.      standard output file.
  824.      Instead of outputting the result of preprocessing, output a rule
  825.      suitable for `make' describing the dependencies of the main source
  826.      file.  The preprocessor outputs one `make' rule containing the
  827.      object file name for that source file, a colon, and the names of
  828.      all the included files.  If there are many included files then the
  829.      rule is split into several lines using `\'-newline.
  830.      This feature is used in automatic updating of makefiles.
  831. `-MM'
  832.      Like `-M' but mention only the files included with `#include
  833.      "FILE"'.  System header files included with `#include <FILE>' are
  834.      omitted.
  835. `-MD'
  836.      Like `-M' but the dependency information is written to files with
  837.      names made by replacing `.c' with `.d' at the end of the input
  838.      file names.  This is in addition to compiling the file as
  839.      specified--`-MD' does not inhibit ordinary compilation the way
  840.      `-M' does.
  841.      In Mach, you can use the utility `md' to merge the `.d' files into
  842.      a single dependency file suitable for using with the `make'
  843.      command.
  844. `-MMD'
  845.      Like `-MD' except mention only user header files, not system
  846.      header files.
  847.      Print the name of each header file used, in addition to other
  848.      normal activities.
  849. `-imacros FILE'
  850.      Process FILE as input, discarding the resulting output, before
  851.      processing the regular input file.  Because the output generated
  852.      from FILE is discarded, the only effect of `-imacros FILE' is to
  853.      make the macros defined in FILE available for use in the main
  854.      input.
  855. `-include FILE'
  856.      Process FILE as input, and include all the resulting output,
  857.      before processing the regular input file.
  858. `-idirafter DIR'
  859.      Add the directory DIR to the second include path.  The directories
  860.      on the second include path are searched when a header file is not
  861.      found in any of the directories in the main include path (the one
  862.      that `-I' adds to).
  863. `-iprefix PREFIX'
  864.      Specify PREFIX as the prefix for subsequent `-iwithprefix' options.
  865. `-iwithprefix DIR'
  866.      Add a directory to the second include path.  The directory's name
  867.      is made by concatenating PREFIX and DIR, where PREFIX was
  868.      specified previously with `-iprefix'.
  869. `-lang-c'
  870. `-lang-c++'
  871. `-lang-objc'
  872. `-lang-objc++'
  873.      Specify the source language.  `-lang-c++' makes the preprocessor
  874.      handle C++ comment syntax (comments may begin with `//', in which
  875.      case they end at end of line), and includes extra default include
  876.      directories for C++; and `-lang-objc' enables the Objective C
  877.      `#import' command.  `-lang-c' explicitly turns off both of these
  878.      extensions, and `-lang-objc++' enables both.
  879.      These options are generated by the compiler driver `gcc', but not
  880.      passed from the `gcc' command line.
  881. `-lint'
  882.      Look for commands to the program checker `lint' embedded in
  883.      comments, and emit them preceded by `#pragma lint'.  For example,
  884.      the comment `/* NOTREACHED */' becomes `#pragma lint NOTREACHED'.
  885.      This option is available only when you call `cpp' directly; `gcc'
  886.      will not pass it from its command line.
  887.      Forbid the use of `$' in identifiers.  This is required for ANSI
  888.      conformance.  `gcc' automatically supplies this option to the
  889.      preprocessor if you specify `-ansi', but `gcc' doesn't recognize
  890.      the `-$' option itself--to use it without the other effects of
  891.      `-ansi', you must call the preprocessor directly.
  892. File: cpp.info,  Node: Concept Index,  Next: Index,  Prev: Invocation,  Up: Top
  893. Concept Index
  894. *************
  895. * Menu:
  896. * assertions:                           Assertions.
  897. * assertions, undoing:                  Assertions.
  898. * cascaded macros:                      Cascaded Macros.
  899. * commands:                             Commands.
  900. * concatenation:                        Concatenation.
  901. * conditionals:                         Conditionals.
  902. * header file:                          Header Files.
  903. * inheritance:                          Inheritance.
  904. * line control:                         Combining Sources.
  905. * macro body uses macro:                Cascaded Macros.
  906. * null command:                         Other Commands.
  907. * options:                              Invocation.
  908. * output format:                        Output.
  909. * overriding a header file:             Inheritance.
  910. * predefined macros:                    Predefined.
  911. * predicates:                           Assertions.
  912. * preprocessor commands:                Commands.
  913. * redefining macros:                    Redefining.
  914. * repeated inclusion:                   Once-Only.
  915. * retracting assertions:                Assertions.
  916. * second include path:                  Invocation.
  917. * self-reference:                       Self-Reference.
  918. * semicolons (after macro calls):       Swallow Semicolon.
  919. * side effects (in macro arguments):    Side Effects.
  920. * stringification:                      Stringification.
  921. * testing predicates:                   Assertions.
  922. * unassert:                             Assertions.
  923. * undefining macros:                    Undefining.
  924. * unsafe macros:                        Side Effects.
  925.