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-1 (.txt) < prev    next >
GNU Info File  |  1994-02-21  |  51KB  |  935 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: Top,  Next: Global Actions,  Up: (DIR)
  16. The C Preprocessor
  17. ******************
  18.    The C preprocessor is a "macro processor" that is used automatically
  19. by the C compiler to transform your program before actual compilation.
  20. It is 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
  23. use as you see fit:
  24.    * Inclusion of header files.  These are files of declarations that
  25.      can be 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
  33.      files into an intermediate file which is then compiled, you can
  34.      use line control to inform the compiler of where each source line
  35.      originally came from.
  36.    C preprocessors vary in some details.  This manual discusses the GNU
  37. C preprocessor, the C Compatible Compiler Preprocessor.  The GNU C
  38. preprocessor provides a superset of the features of ANSI Standard C.
  39.    ANSI Standard C requires the rejection of many harmless constructs
  40. commonly used by today's C programs.  Such incompatibility would be
  41. inconvenient for users, so the GNU C preprocessor is configured to
  42. accept these constructs by default.  Strictly speaking, to get ANSI
  43. Standard C, you must use the options `-trigraphs', `-undef' and
  44. `-pedantic', but in practice the consequences of having strict ANSI
  45. Standard C make it undesirable to do this.  *Note Invocation::.
  46. * Menu:
  47. * Global Actions::    Actions made uniformly on all input files.
  48. * Commands::          General syntax of preprocessor commands.
  49. * Header Files::      How and why to use header files.
  50. * Macros::            How and why to use macros.
  51. * Conditionals::      How and why to use conditionals.
  52. * Combining Sources:: Use of line control when you combine source files.
  53. * Other Commands::    Miscellaneous preprocessor commands.
  54. * Output::            Format of output from the C preprocessor.
  55. * Invocation::        How to invoke the preprocessor; command options.
  56. * Concept Index::     Index of concepts and terms.
  57. * Index::             Index of commands, predefined macros and options.
  58. File: cpp.info,  Node: Global Actions,  Next: Commands,  Prev: Top,  Up: Top
  59. Transformations Made Globally
  60. =============================
  61.    Most C preprocessor features are inactive unless you give specific
  62. commands to request their use.  (Preprocessor commands are lines
  63. starting with `#'; *note Commands::.).  But there are three
  64. transformations that the preprocessor always makes on all the input it
  65. receives, even in the absence 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
  69.      without changing their meaning.
  70.    * Predefined macro names are replaced with their expansions (*note
  71.      Predefined::.).
  72.    The first two transformations are done *before* nearly all other
  73. parsing and before preprocessor commands are recognized.  Thus, for
  74. example, you can split a line cosmetically with Backslash-Newline
  75. anywhere (except when trigraphs are in use; see below).
  76.      /*
  77.      */ # /*
  78.      */ defi\
  79.      ne FO\
  80.      O 10\
  81.      20
  82. is equivalent into `#define FOO 1020'.  You can split even an escape
  83. sequence with Backslash-Newline.  For example, you can split `"foo\bar"'
  84. between the `\' and the `b' to get
  85.      "foo\\
  86.      bar"
  87. This behavior is unclean: in all other contexts, a Backslash can be
  88. inserted in a string constant as an ordinary character by writing a
  89. double Backslash, and this creates an exception.  But the ANSI C
  90. standard requires it.  (Strict ANSI C does not allow Newlines in string
  91. constants, so they do not consider this a problem.)
  92.    But there are a few exceptions to all three transformations.
  93.    * C comments and predefined macro names are not recognized inside a
  94.      `#include' command in which the file name is delimited with `<'
  95.      and `>'.
  96.    * C comments and predefined macro names are never recognized within a
  97.      character or string constant.  (Strictly speaking, this is the
  98.      rule, not an exception, but it is worth noting here anyway.)
  99.    * Backslash-Newline may not safely be used within an ANSI "trigraph".
  100.      Trigraphs are converted before Backslash-Newline is deleted.  If
  101.      you write what looks like a trigraph with a Backslash-Newline
  102.      inside, the Backslash-Newline is deleted as usual, but it is then
  103.      too late to recognize the trigraph.
  104.      This exception is relevant only if you use the `-trigraphs' option
  105.      to enable trigraph processing.  *Note Invocation::.
  106. File: cpp.info,  Node: Commands,  Next: Header Files,  Prev: Global Actions,  Up: Top
  107. Preprocessor Commands
  108. =====================
  109.    Most preprocessor features are active only if you use preprocessor
  110. commands to request their use.
  111.    Preprocessor commands are lines in your program that start with `#'.
  112. The `#' is followed by an identifier that is the "command name".  For
  113. example, `#define' is the command that defines a macro.  Whitespace is
  114. also allowed before and after the `#'.
  115.    The set of valid command names is fixed.  Programs cannot define new
  116. preprocessor commands.
  117.    Some command names require arguments; these make up the rest of the
  118. command line and must be separated from the command name by whitespace.
  119. For example, `#define' must be followed by a macro name and the
  120. intended expansion of the macro.
  121.    A preprocessor command cannot be more than one line in normal
  122. circumstances.  It may be split cosmetically with Backslash-Newline,
  123. but that has no effect on its meaning.  Comments containing Newlines
  124. can also divide the command into multiple lines, but the comments are
  125. changed to Spaces before the command is interpreted.  The only way a
  126. significant Newline can occur in a preprocessor command is within a
  127. string constant or character constant.  Note that most C compilers that
  128. might be applied to the output from the preprocessor do not accept
  129. string or character constants containing Newlines.
  130.    The `#' and the command name cannot come from a macro expansion.  For
  131. example, if `foo' is defined as a macro expanding to `define', that
  132. does not make `#foo' a valid preprocessor command.
  133. File: cpp.info,  Node: Header Files,  Next: Macros,  Prev: Commands,  Up: Top
  134. Header Files
  135. ============
  136.    A header file is a file containing C declarations and macro
  137. definitions (*note Macros::.) to be shared between several source
  138. files.  You request the use of a header file in your program with the C
  139. preprocessor command `#include'.
  140. * Menu:
  141. * Header Uses::         What header files are used for.
  142. * Include Syntax::      How to write `#include' commands.
  143. * Include Operation::   What `#include' does.
  144. * Once-Only::        Preventing multiple inclusion of one header file.
  145. * Inheritance::         Including one header file in another header file.
  146. File: cpp.info,  Node: Header Uses,  Next: Include Syntax,  Prev: Header Files,  Up: Header Files
  147. Uses of Header Files
  148. --------------------
  149.    Header files serve two kinds of purposes.
  150.    * System header files declare the interfaces to parts of the
  151.      operating system.  You include them in your program to supply the
  152.      definitions and declarations you need to invoke system calls and
  153.      libraries.
  154.    * Your own header files contain declarations for interfaces between
  155.      the source files of your program.  Each time you have a group of
  156.      related declarations and macro definitions all or most of which
  157.      are needed in several different source files, it is a good idea to
  158.      create a header file for them.
  159.    Including a header file produces the same results in C compilation as
  160. copying the header file into each source file that needs it.  But such
  161. copying would be time-consuming and error-prone.  With a header file,
  162. the related declarations appear in only one place.  If they need to be
  163. changed, they can be changed in one place, and programs that include
  164. the header file will automatically use the new version when next
  165. recompiled.  The header file eliminates the labor of finding and
  166. changing all the copies as well as the risk that a failure to find one
  167. copy will result in inconsistencies within a program.
  168.    The usual convention is to give header files names that end with
  169. `.h'.
  170. File: cpp.info,  Node: Include Syntax,  Next: Include Operation,  Prev: Header Uses,  Up: Header Files
  171. The `#include' Command
  172. ----------------------
  173.    Both user and system header files are included using the preprocessor
  174. command `#include'.  It has three variants:
  175. `#include <FILE>'
  176.      This variant is used for system header files.  It searches for a
  177.      file named FILE in a list of directories specified by you, then in
  178.      a standard list of system directories.  You specify directories to
  179.      search for header files with the command option `-I' (*note
  180.      Invocation::.).  The option `-nostdinc' inhibits searching the
  181.      standard system directories; in this case only the directories you
  182.      specify are searched.
  183.      The parsing of this form of `#include' is slightly special because
  184.      comments are not recognized within the `<...>'.  Thus, in
  185.      `#include <x/*y>' the `/*' does not start a comment and the
  186.      command specifies inclusion of a system header file named `x/*y'.
  187.      Of course, a header file with such a name is unlikely to exist on
  188.      Unix, where shell wildcard features would make it hard to
  189.      manipulate.
  190.      The argument FILE may not contain a `>' character.  It may,
  191.      however, contain a `<' character.
  192. `#include "FILE"'
  193.      This variant is used for header files of your own program.  It
  194.      searches for a file named FILE first in the current directory,
  195.      then in the same directories used for system header files.  The
  196.      current directory is the directory of the current input file.  It
  197.      is tried first because it is presumed to be the location of the
  198.      files that the current input file refers to.  (If the `-I-' option
  199.      is used, the special treatment of the current directory is
  200.      inhibited.)
  201.      The argument FILE may not contain `"' characters.  If backslashes
  202.      occur within FILE, they are considered ordinary text characters,
  203.      not escape characters.  None of the character escape sequences
  204.      appropriate to string constants in C are processed.  Thus,
  205.      `#include "x\n\\y"' specifies a filename containing three
  206.      backslashes.  It is not clear why this behavior is ever useful, but
  207.      the ANSI standard specifies it.
  208. `#include ANYTHING ELSE'
  209.      This variant is called a "computed #include".  Any `#include'
  210.      command whose argument does not fit the above two forms is a
  211.      computed include.  The text ANYTHING ELSE is checked for macro
  212.      calls, which are expanded (*note Macros::.).  When this is done,
  213.      the result must fit one of the above two variants--in particular,
  214.      the expanded text must in the end be surrounded by either quotes
  215.      or angle braces.
  216.      This feature allows you to define a macro which controls the file
  217.      name to be used at a later point in the program.  One application
  218.      of this is to allow a site-configuration file for your program to
  219.      specify the names of the system include files to be used.  This
  220.      can help in porting the program to various operating systems in
  221.      which the necessary system header files are found in different
  222.      places.
  223. File: cpp.info,  Node: Include Operation,  Next: Once-Only,  Prev: Include Syntax,  Up: Header Files
  224. How `#include' Works
  225. --------------------
  226.    The `#include' command works by directing the C preprocessor to scan
  227. the specified file as input before continuing with the rest of the
  228. current file.  The output from the preprocessor contains the output
  229. already generated, followed by the output resulting from the included
  230. file, followed by the output that comes from the text after the
  231. `#include' command.  For example, given two files as follows:
  232.      /* File program.c */
  233.      int x;
  234.      #include "header.h"
  235.      
  236.      main ()
  237.      {
  238.        printf (test ());
  239.      }
  240.      
  241.      
  242.      /* File header.h */
  243.      char *test ();
  244. the output generated by the C preprocessor for `program.c' as input
  245. would be
  246.      int x;
  247.      char *test ();
  248.      
  249.      main ()
  250.      {
  251.        printf (test ());
  252.      }
  253.    Included files are not limited to declarations and macro
  254. definitions; those are merely the typical uses.  Any fragment of a C
  255. program can be included from another file.  The include file could even
  256. contain the beginning of a statement that is concluded in the
  257. containing file, or the end of a statement that was started in the
  258. including file.  However, a comment or a string or character constant
  259. may not start in the included file and finish in the including file.
  260. An unterminated comment, string constant or character constant in an
  261. included file is considered to end (with an error message) at the end
  262. of the file.
  263.    The line following the `#include' command is always treated as a
  264. separate line by the C preprocessor even if the included file lacks a
  265. final newline.
  266. File: cpp.info,  Node: Once-Only,  Next: Inheritance,  Prev: Include Operation,  Up: Header Files
  267. Once-Only Include Files
  268. -----------------------
  269.    Very often, one header file includes another.  It can easily result
  270. that a certain header file is included more than once.  This may lead
  271. to errors, if the header file defines structure types or typedefs, and
  272. is certainly wasteful.  Therefore, we often wish to prevent multiple
  273. inclusion of a header file.
  274.    The standard way to do this is to enclose the entire real contents
  275. of the file in a conditional, like this:
  276.      #ifndef __FILE_FOO_SEEN__
  277.      #define __FILE_FOO_SEEN__
  278.      
  279.      THE ENTIRE FILE
  280.      
  281.      #endif /* __FILE_FOO_SEEN__ */
  282.    The macro `__FILE_FOO_SEEN__' indicates that the file has been
  283. included once already; its name should begin with `__' to avoid
  284. conflicts with user programs, and it should contain the name of the file
  285. and some additional text, to avoid conflicts with other header files.
  286.    The GNU C preprocessor is programmed to notice when a header file
  287. uses this particular construct and handle it efficiently.  If a header
  288. file is contained entirely in a `#ifndef' conditional, then it records
  289. that fact.  If a subsequent `#include' specifies the same file, and the
  290. macro in the `#ifndef' is already defined, then the file is entirely
  291. skipped, without even reading it.
  292.    There is also an explicit command to tell the preprocessor that it
  293. need not include a file more than once.  This is called `#pragma once',
  294. and was used *in addition to* the `#ifndef' conditional around the
  295. contents of the header file.  `#pragma once' is now obsolete and should
  296. not be used at all.
  297.    In the Objective C language, there is a variant of `#include' called
  298. `#import' which includes a file, but does so at most once.  If you use
  299. `#import' *instead of* `#include', then you don't need the conditionals
  300. inside the header file to prevent multiple execution of the contents.
  301.    `#import' is obsolete because it is not a well-designed feature.  It
  302. requires the users of a header file--the applications programmers--to
  303. know that a certain header file should only be included once.  It is
  304. much better for the header file's implementor to write the file so that
  305. users don't need to know this.  Using `#ifndef' accomplishes this goal.
  306. File: cpp.info,  Node: Inheritance,  Prev: Once-Only,  Up: Header Files
  307. Inheritance and Header Files
  308. ============================
  309.    "Inheritance" is what happens when one object or file derives some
  310. of its contents by virtual copying from another object or file.  In the
  311. case of C header files, inheritance means that one header file includes
  312. another header file and then replaces or adds something.
  313.    If the inheriting header file and the base header file have different
  314. names, then inheritance is straightforward: simply write `#include
  315. "BASE"' in the inheriting file.
  316.    Sometimes it is necessary to give the inheriting file the same name
  317. as the base file.  This is less straightforward.
  318.    For example, suppose an application program uses the system header
  319. file `sys/signal.h', but the version of `/usr/include/sys/signal.h' on
  320. a particular system doesn't do what the application program expects.
  321. It might be convenient to define a "local" version, perhaps under the
  322. name `/gnu/include/sys/signal.h', to override or add to the one
  323. supplied by the system.
  324.    You can do this by using the option `-I.' for compilation, and
  325. writing a file `sys/signal.h' that does what the application program
  326. expects.  But making this file include the standard `sys/signal.h' is
  327. not so easy--writing `#include <sys/signal.h>' in that file doesn't
  328. work, because it includes your own version of the file, not the
  329. standard system version.  Used in that file itself, this leads to an
  330. infinite recursion and a fatal error in compilation.
  331.    `#include </usr/include/sys/signal.h>' would find the proper file,
  332. but that is not clean, since it makes an assumption about where the
  333. system header file is found.  This is bad for maintenance, since it
  334. means that any change in where the system's header files are kept
  335. requires a change somewhere else.
  336.    The clean way to solve this problem is to use `#include_next', which
  337. means, "Include the *next* file with this name."  This command works
  338. like `#include' except in searching for the specified file: it starts
  339. searching the list of header file directories *after* the directory in
  340. which the current file was found.
  341.    Suppose you specify `-I /gnu/include', and the list of directories
  342. to search also includes `/usr/include'; and suppose that both
  343. directories contain a file named `sys/signal.h'.  Ordinary `#include
  344. <sys/signal.h>' finds the file under `/gnu/include'.  If that file
  345. contains `#include_next <sys/signal.h>', it starts searching after that
  346. directory, and finds the file in `/usr/include'.
  347. File: cpp.info,  Node: Macros,  Next: Conditionals,  Prev: Header Files,  Up: Top
  348. Macros
  349. ======
  350.    A macro is a sort of abbreviation which you can define once and then
  351. use later.  There are many complicated features associated with macros
  352. in the C preprocessor.
  353. * Menu:
  354. * Simple Macros::    Macros that always expand the same way.
  355. * Argument Macros::  Macros that accept arguments that are substituted
  356.                        into the macro expansion.
  357. * Predefined::       Predefined macros that are always available.
  358. * Stringification::  Macro arguments converted into string constants.
  359. * Concatenation::    Building tokens from parts taken from macro arguments.
  360. * Undefining::       Cancelling a macro's definition.
  361. * Redefining::       Changing a macro's definition.
  362. * Macro Pitfalls::   Macros can confuse the unwary.  Here we explain
  363.                        several common problems and strange features.
  364. File: cpp.info,  Node: Simple Macros,  Next: Argument Macros,  Prev: Macros,  Up: Macros
  365. Simple Macros
  366. -------------
  367.    A "simple macro" is a kind of abbreviation.  It is a name which
  368. stands for a fragment of code.  Some people refer to these as "manifest
  369. constants".
  370.    Before you can use a macro, you must "define" it explicitly with the
  371. `#define' command.  `#define' is followed by the name of the macro and
  372. then the code it should be an abbreviation for.  For example,
  373.      #define BUFFER_SIZE 1020
  374. defines a macro named `BUFFER_SIZE' as an abbreviation for the text
  375. `1020'.  Therefore, if somewhere after this `#define' command there
  376. comes a C statement of the form
  377.      foo = (char *) xmalloc (BUFFER_SIZE);
  378. then the C preprocessor will recognize and "expand" the macro
  379. `BUFFER_SIZE', resulting in
  380.      foo = (char *) xmalloc (1020);
  381. the definition must be a single line; however, it may not end in the
  382. middle of a multi-line string constant or character constant.
  383.    The use of all upper case for macro names is a standard convention.
  384. Programs are easier to read when it is possible to tell at a glance
  385. which names are macros.
  386.    Normally, a macro definition must be a single line, like all C
  387. preprocessor commands.  (You can split a long macro definition
  388. cosmetically with Backslash-Newline.)  There is one exception: Newlines
  389. can be included in the macro definition if within a string or character
  390. constant.  By the same token, it is not possible for a macro definition
  391. to contain an unbalanced quote character; the definition automatically
  392. extends to include the matching quote character that ends the string or
  393. character constant.  Comments within a macro definition may contain
  394. Newlines, which make no difference since the comments are entirely
  395. replaced with Spaces regardless of their contents.
  396.    Aside from the above, there is no restriction on what can go in a
  397. macro body.  Parentheses need not balance.  The body need not resemble
  398. valid C code.  (Of course, you might get error messages from the C
  399. compiler when you use the macro.)
  400.    The C preprocessor scans your program sequentially, so macro
  401. definitions take effect at the place you write them.  Therefore, the
  402. following input to the C preprocessor
  403.      foo = X;
  404.      #define X 4
  405.      bar = X;
  406. produces as output
  407.      foo = X;
  408.      
  409.      bar = 4;
  410.    After the preprocessor expands a macro name, the macro's definition
  411. body is appended to the front of the remaining input, and the check for
  412. macro calls continues.  Therefore, the macro body can contain calls to
  413. other macros.  For example, after
  414.      #define BUFSIZE 1020
  415.      #define TABLESIZE BUFSIZE
  416. the name `TABLESIZE' when used in the program would go through two
  417. stages of expansion, resulting ultimately in `1020'.
  418.    This is not at all the same as defining `TABLESIZE' to be `1020'.
  419. The `#define' for `TABLESIZE' uses exactly the body you specify--in
  420. this case, `BUFSIZE'--and does not check to see whether it too is the
  421. name of a macro.  It's only when you *use* `TABLESIZE' that the result
  422. of its expansion is checked for more macro names.  *Note Cascaded
  423. Macros::.
  424. File: cpp.info,  Node: Argument Macros,  Next: Predefined,  Prev: Simple Macros,  Up: Macros
  425. Macros with Arguments
  426. ---------------------
  427.    A simple macro always stands for exactly the same text, each time it
  428. is used.  Macros can be more flexible when they accept "arguments".
  429. Arguments are fragments of code that you supply each time the macro is
  430. used.  These fragments are included in the expansion of the macro
  431. according to the directions in the macro definition.
  432.    To define a macro that uses arguments, you write a `#define' command
  433. with a list of "argument names" in parentheses after the name of the
  434. macro.  The argument names may be any valid C identifiers, separated by
  435. commas and optionally whitespace.  The open-parenthesis must follow the
  436. macro name immediately, with no space in between.
  437.    For example, here is a macro that computes the minimum of two numeric
  438. values, as it is defined in many C programs:
  439.      #define min(X, Y)  ((X) < (Y) ? (X) : (Y))
  440. (This is not the best way to define a "minimum" macro in GNU C.  *Note
  441. Side Effects::, for more information.)
  442.    To use a macro that expects arguments, you write the name of the
  443. macro followed by a list of "actual arguments" in parentheses,
  444. separated by commas.  The number of actual arguments you give must
  445. match the number of arguments the macro expects.   Examples of use of
  446. the macro `min' include `min (1, 2)' and `min (x + 28, *p)'.
  447.    The expansion text of the macro depends on the arguments you use.
  448. Each of the argument names of the macro is replaced, throughout the
  449. macro definition, with the corresponding actual argument.  Using the
  450. same macro `min' defined above, `min (1, 2)' expands into
  451.      ((1) < (2) ? (1) : (2))
  452. where `1' has been substituted for `X' and `2' for `Y'.
  453.    Likewise, `min (x + 28, *p)' expands into
  454.      ((x + 28) < (*p) ? (x + 28) : (*p))
  455.    Parentheses in the actual arguments must balance; a comma within
  456. parentheses does not end an argument.  However, there is no requirement
  457. for brackets or braces to balance, and they do not prevent a comma from
  458. separating arguments.  Thus,
  459.      macro (array[x = y, x + 1])
  460. passes two arguments to `macro': `array[x = y' and `x + 1]'.  If you
  461. want to supply `array[x = y, x + 1]' as an argument, you must write it
  462. as `array[(x = y, x + 1)]', which is equivalent C code.
  463.    After the actual arguments are substituted into the macro body, the
  464. entire result is appended to the front of the remaining input, and the
  465. check for macro calls continues.  Therefore, the actual arguments can
  466. contain calls to other macros, either with or without arguments, or
  467. even to the same macro.  The macro body can also contain calls to other
  468. macros.  For example, `min (min (a, b), c)' expands into this text:
  469.      ((((a) < (b) ? (a) : (b))) < (c)
  470.       ? (((a) < (b) ? (a) : (b)))
  471.       : (c))
  472. (Line breaks shown here for clarity would not actually be generated.)
  473.    If a macro `foo' takes one argument, and you want to supply an empty
  474. argument, you must write at least some whitespace between the
  475. parentheses, like this: `foo ( )'.  Just `foo ()' is providing no
  476. arguments, which is an error if `foo' expects an argument.  But `foo0
  477. ()' is the correct way to call a macro defined to take zero arguments,
  478. like this:
  479.      #define foo0() ...
  480.    If you use the macro name followed by something other than an
  481. open-parenthesis (after ignoring any spaces, tabs and comments that
  482. follow), it is not a call to the macro, and the preprocessor does not
  483. change what you have written.  Therefore, it is possible for the same
  484. name to be a variable or function in your program as well as a macro,
  485. and you can choose in each instance whether to refer to the macro (if
  486. an actual argument list follows) or the variable or function (if an
  487. argument list does not follow).
  488.    Such dual use of one name could be confusing and should be avoided
  489. except when the two meanings are effectively synonymous: that is, when
  490. the name is both a macro and a function and the two have similar
  491. effects.  You can think of the name simply as a function; use of the
  492. name for purposes other than calling it (such as, to take the address)
  493. will refer to the function, while calls will expand the macro and
  494. generate better but equivalent code.  For example, you can use a
  495. function named `min' in the same source file that defines the macro.
  496. If you write `&min' with no argument list, you refer to the function.
  497. If you write `min (x, bb)', with an argument list, the macro is
  498. expanded.  If you write `(min) (a, bb)', where the name `min' is not
  499. followed by an open-parenthesis, the macro is not expanded, so you wind
  500. up with a call to the function `min'.
  501.    You may not define the same name as both a simple macro and a macro
  502. with arguments.
  503.    In the definition of a macro with arguments, the list of argument
  504. names must follow the macro name immediately with no space in between.
  505. If there is a space after the macro name, the macro is defined as
  506. taking no arguments, and all the rest of the line is taken to be the
  507. expansion.  The reason for this is that it is often useful to define a
  508. macro that takes no arguments and whose definition begins with an
  509. identifier in parentheses.  This rule about spaces makes it possible
  510. for you to do either this:
  511.      #define FOO(x) - 1 / (x)
  512. (which defines `FOO' to take an argument and expand into minus the
  513. reciprocal of that argument) or this:
  514.      #define BAR (x) - 1 / (x)
  515. (which defines `BAR' to take no argument and always expand into `(x) -
  516. 1 / (x)').
  517.    Note that the *uses* of a macro with arguments can have spaces before
  518. the left parenthesis; it's the *definition* where it matters whether
  519. there is a space.
  520. File: cpp.info,  Node: Predefined,  Next: Stringification,  Prev: Argument Macros,  Up: Macros
  521. Predefined Macros
  522. -----------------
  523.    Several simple macros are predefined.  You can use them without
  524. giving definitions for them.  They fall into two classes: standard
  525. macros and system-specific macros.
  526. * Menu:
  527. * Standard Predefined::     Standard predefined macros.
  528. * Nonstandard Predefined::  Nonstandard predefined macros.
  529. File: cpp.info,  Node: Standard Predefined,  Next: Nonstandard Predefined,  Prev: Predefined,  Up: Predefined
  530. Standard Predefined Macros
  531. ..........................
  532.    The standard predefined macros are available with the same meanings
  533. regardless of the machine or operating system on which you are using
  534. GNU C.  Their names all start and end with double underscores.  Those
  535. preceding `__GNUC__' in this table are standardized by ANSI C; the rest
  536. are GNU C extensions.
  537. `__FILE__'
  538.      This macro expands to the name of the current input file, in the
  539.      form of a C string constant.  The precise name returned is the one
  540.      that was specified in `#include' or as the input file name
  541.      argument.
  542. `__LINE__'
  543.      This macro expands to the current input line number, in the form
  544.      of a decimal integer constant.  While we call it a predefined
  545.      macro, it's a pretty strange macro, since its "definition" changes
  546.      with each new line of source code.
  547.      This and `__FILE__' are useful in generating an error message to
  548.      report an inconsistency detected by the program; the message can
  549.      state the source line at which the inconsistency was detected.
  550.      For example,
  551.           fprintf (stderr, "Internal error: "
  552.                    "negative string length "
  553.                            "%d at %s, line %d.",
  554.                    length, __FILE__, __LINE__);
  555.      A `#include' command changes the expansions of `__FILE__' and
  556.      `__LINE__' to correspond to the included file.  At the end of that
  557.      file, when processing resumes on the input file that contained the
  558.      `#include' command, the expansions of `__FILE__' and `__LINE__'
  559.      revert to the values they had before the `#include' (but
  560.      `__LINE__' is then incremented by one as processing moves to the
  561.      line after the `#include').
  562.      The expansions of both `__FILE__' and `__LINE__' are altered if a
  563.      `#line' command is used.  *Note Combining Sources::.
  564. `__INCLUDE_LEVEL__'
  565.      This macro expands to a decimal integer constant that represents
  566.      the depth of nesting in include files.  The value of this macro is
  567.      incremented on every `#include' command and decremented at every
  568.      end of file.
  569. `__DATE__'
  570.      This macro expands to a string constant that describes the date on
  571.      which the preprocessor is being run.  The string constant contains
  572.      eleven characters and looks like `"Jan 29 1987"' or `"Apr 1 1905"'.
  573. `__TIME__'
  574.      This macro expands to a string constant that describes the time at
  575.      which the preprocessor is being run.  The string constant contains
  576.      eight characters and looks like `"23:59:01"'.
  577. `__STDC__'
  578.      This macro expands to the constant 1, to signify that this is ANSI
  579.      Standard C.  (Whether that is actually true depends on what C
  580.      compiler will operate on the output from the preprocessor.)
  581. `__GNUC__'
  582.      This macro is defined if and only if this is GNU C.  This macro is
  583.      defined only when the entire GNU C compiler is in use; if you
  584.      invoke the preprocessor directly, `__GNUC__' is undefined.
  585. `__GNUG__'
  586.      The GNU C compiler defines this when the compilation language is
  587.      C++; use `__GNUG__' to distinguish between GNU C and GNU C++.
  588. `__cplusplus'
  589.      The draft ANSI standard for C++ used to require predefining this
  590.      variable.  Though it is no longer required, GNU C++ continues to
  591.      define it, as do other popular C++ compilers.  You can use
  592.      `__cplusplus' to test whether a header is compiled by a C compiler
  593.      or a C++ compiler.
  594. `__STRICT_ANSI__'
  595.      This macro is defined if and only if the `-ansi' switch was
  596.      specified when GNU C was invoked.  Its definition is the null
  597.      string.  This macro exists primarily to direct certain GNU header
  598.      files not to define certain traditional Unix constructs which are
  599.      incompatible with ANSI C.
  600. `__BASE_FILE__'
  601.      This macro expands to the name of the main input file, in the form
  602.      of a C string constant.  This is the source file that was specified
  603.      as an argument when the C compiler was invoked.
  604. `__VERSION__'
  605.      This macro expands to a string which describes the version number
  606.      of GNU C.  The string is normally a sequence of decimal numbers
  607.      separated by periods, such as `"1.18"'.  The only reasonable use
  608.      of this macro is to incorporate it into a string constant.
  609. `__OPTIMIZE__'
  610.      This macro is defined in optimizing compilations.  It causes
  611.      certain GNU header files to define alternative macro definitions
  612.      for some system library functions.  It is unwise to refer to or
  613.      test the definition of this macro unless you make very sure that
  614.      programs will execute with the same effect regardless.
  615. `__CHAR_UNSIGNED__'
  616.      This macro is defined if and only if the data type `char' is
  617.      unsigned on the target machine.  It exists to cause the standard
  618.      header file `limit.h' to work correctly.  It is bad practice to
  619.      refer to this macro yourself; instead, refer to the standard
  620.      macros defined in `limit.h'.  The preprocessor uses this macro to
  621.      determine whether or not to sign-extend large character constants
  622.      written in octal; see *Note The `#if' Command: #if Command.
  623. File: cpp.info,  Node: Nonstandard Predefined,  Prev: Standard Predefined,  Up: Predefined
  624. Nonstandard Predefined Macros
  625. .............................
  626.    The C preprocessor normally has several predefined macros that vary
  627. between machines because their purpose is to indicate what type of
  628. system and machine is in use.  This manual, being for all systems and
  629. machines, cannot tell you exactly what their names are; instead, we
  630. offer a list of some typical ones.  You can use `cpp -dM' to see the
  631. values of predefined macros; *note Invocation::..
  632.    Some nonstandard predefined macros describe the operating system in
  633. use, with more or less specificity.  For example,
  634. `unix'
  635.      `unix' is normally predefined on all Unix systems.
  636. `BSD'
  637.      `BSD' is predefined on recent versions of Berkeley Unix (perhaps
  638.      only in version 4.3).
  639.    Other nonstandard predefined macros describe the kind of CPU, with
  640. more or less specificity.  For example,
  641. `vax'
  642.      `vax' is predefined on Vax computers.
  643. `mc68000'
  644.      `mc68000' is predefined on most computers whose CPU is a Motorola
  645.      68000, 68010 or 68020.
  646. `m68k'
  647.      `m68k' is also predefined on most computers whose CPU is a 68000,
  648.      68010 or 68020; however, some makers use `mc68000' and some use
  649.      `m68k'.  Some predefine both names.  What happens in GNU C depends
  650.      on the system you are using it on.
  651. `M68020'
  652.      `M68020' has been observed to be predefined on some systems that
  653.      use 68020 CPUs--in addition to `mc68000' and `m68k', which are
  654.      less specific.
  655. `_AM29K'
  656. `_AM29000'
  657.      Both `_AM29K' and `_AM29000' are predefined for the AMD 29000 CPU
  658.      family.
  659. `ns32000'
  660.      `ns32000' is predefined on computers which use the National
  661.      Semiconductor 32000 series CPU.
  662.    Yet other nonstandard predefined macros describe the manufacturer of
  663. the system.  For example,
  664. `sun'
  665.      `sun' is predefined on all models of Sun computers.
  666. `pyr'
  667.      `pyr' is predefined on all models of Pyramid computers.
  668. `sequent'
  669.      `sequent' is predefined on all models of Sequent computers.
  670.    These predefined symbols are not only nonstandard, they are contrary
  671. to the ANSI standard because their names do not start with underscores.
  672. Therefore, the option `-ansi' inhibits the definition of these symbols.
  673.    This tends to make `-ansi' useless, since many programs depend on the
  674. customary nonstandard predefined symbols.  Even system header files
  675. check them and will generate incorrect declarations if they do not find
  676. the names that are expected.  You might think that the header files
  677. supplied for the Uglix computer would not need to test what machine
  678. they are running on, because they can simply assume it is the Uglix;
  679. but often they do, and they do so using the customary names.  As a
  680. result, very few C programs will compile with `-ansi'.  We intend to
  681. avoid such problems on the GNU system.
  682.    What, then, should you do in an ANSI C program to test the type of
  683. machine it will run on?
  684.    GNU C offers a parallel series of symbols for this purpose, whose
  685. names are made from the customary ones by adding `__' at the beginning
  686. and end.  Thus, the symbol `__vax__' would be available on a Vax, and
  687. so on.
  688.    The set of nonstandard predefined names in the GNU C preprocessor is
  689. controlled (when `cpp' is itself compiled) by the macro
  690. `CPP_PREDEFINES', which should be a string containing `-D' options,
  691. separated by spaces.  For example, on the Sun 3, we use the following
  692. definition:
  693.      #define CPP_PREDEFINES "-Dmc68000 -Dsun -Dunix -Dm68k"
  694. This macro is usually specified in `tm.h'.
  695. File: cpp.info,  Node: Stringification,  Next: Concatenation,  Prev: Predefined,  Up: Macros
  696. Stringification
  697. ---------------
  698.    "Stringification" means turning a code fragment into a string
  699. constant whose contents are the text for the code fragment.  For
  700. example, stringifying `foo (z)' results in `"foo (z)"'.
  701.    In the C preprocessor, stringification is an option available when
  702. macro arguments are substituted into the macro definition.  In the body
  703. of the definition, when an argument name appears, the character `#'
  704. before the name specifies stringification of the corresponding actual
  705. argument when it is substituted at that point in the definition.  The
  706. same argument may be substituted in other places in the definition
  707. without stringification if the argument name appears in those places
  708. with no `#'.
  709.    Here is an example of a macro definition that uses stringification:
  710.      #define WARN_IF(EXP) \
  711.      do { if (EXP) \
  712.              fprintf (stderr, "Warning: " #EXP "\n"); } \
  713.      while (0)
  714. Here the actual argument for `EXP' is substituted once as given, into
  715. the `if' statement, and once as stringified, into the argument to
  716. `fprintf'.  The `do' and `while (0)' are a kludge to make it possible
  717. to write `WARN_IF (ARG);', which the resemblance of `WARN_IF' to a
  718. function would make C programmers want to do; *note Swallow
  719. Semicolon::.).
  720.    The stringification feature is limited to transforming one macro
  721. argument into one string constant: there is no way to combine the
  722. argument with other text and then stringify it all together.  But the
  723. example above shows how an equivalent result can be obtained in ANSI
  724. Standard C using the feature that adjacent string constants are
  725. concatenated as one string constant.  The preprocessor stringifies the
  726. actual value of `EXP' into a separate string constant, resulting in
  727. text like
  728.      do { if (x == 0) \
  729.              fprintf (stderr, "Warning: " "x == 0" "\n"); } \
  730.      while (0)
  731. but the C compiler then sees three consecutive string constants and
  732. concatenates them into one, producing effectively
  733.      do { if (x == 0) \
  734.              fprintf (stderr, "Warning: x == 0\n"); } \
  735.      while (0)
  736.    Stringification in C involves more than putting doublequote
  737. characters around the fragment; it is necessary to put backslashes in
  738. front of all doublequote characters, and all backslashes in string and
  739. character constants, in order to get a valid C string constant with the
  740. proper contents.  Thus, stringifying `p = "foo\n";' results in `"p =
  741. \"foo\\n\";"'.  However, backslashes that are not inside of string or
  742. character constants are not duplicated: `\n' by itself stringifies to
  743. `"\n"'.
  744.    Whitespace (including comments) in the text being stringified is
  745. handled according to precise rules.  All leading and trailing
  746. whitespace is ignored.  Any sequence of whitespace in the middle of the
  747. text is converted to a single space in the stringified result.
  748. File: cpp.info,  Node: Concatenation,  Next: Undefining,  Prev: Stringification,  Up: Macros
  749. Concatenation
  750. -------------
  751.    "Concatenation" means joining two strings into one.  In the context
  752. of macro expansion, concatenation refers to joining two lexical units
  753. into one longer one.  Specifically, an actual argument to the macro can
  754. be concatenated with another actual argument or with fixed text to
  755. produce a longer name.  The longer name might be the name of a function,
  756. variable or type, or a C keyword; it might even be the name of another
  757. macro, in which case it will be expanded.
  758.    When you define a macro, you request concatenation with the special
  759. operator `##' in the macro body.  When the macro is called, after
  760. actual arguments are substituted, all `##' operators are deleted, and
  761. so is any whitespace next to them (including whitespace that was part
  762. of an actual argument).  The result is to concatenate the syntactic
  763. tokens on either side of the `##'.
  764.    Consider a C program that interprets named commands.  There probably
  765. needs to be a table of commands, perhaps an array of structures
  766. declared as follows:
  767.      struct command
  768.      {
  769.        char *name;
  770.        void (*function) ();
  771.      };
  772.      
  773.      struct command commands[] =
  774.      {
  775.        { "quit", quit_command},
  776.        { "help", help_command},
  777.        ...
  778.      };
  779.    It would be cleaner not to have to give each command name twice,
  780. once in the string constant and once in the function name.  A macro
  781. which takes the name of a command as an argument can make this
  782. unnecessary.  The string constant can be created with stringification,
  783. and the function name by concatenating the argument with `_command'.
  784. Here is how it is done:
  785.      #define COMMAND(NAME)  { #NAME, NAME ## _command }
  786.      
  787.      struct command commands[] =
  788.      {
  789.        COMMAND (quit),
  790.        COMMAND (help),
  791.        ...
  792.      };
  793.    The usual case of concatenation is concatenating two names (or a
  794. name and a number) into a longer name.  But this isn't the only valid
  795. case.  It is also possible to concatenate two numbers (or a number and
  796. a name, such as `1.5' and `e3') into a number.  Also, multi-character
  797. operators such as `+=' can be formed by concatenation.  In some cases
  798. it is even possible to piece together a string constant.  However, two
  799. pieces of text that don't together form a valid lexical unit cannot be
  800. concatenated.  For example, concatenation with `x' on one side and `+'
  801. on the other is not meaningful because those two characters can't fit
  802. together in any lexical unit of C.  The ANSI standard says that such
  803. attempts at concatenation are undefined, but in the GNU C preprocessor
  804. it is well defined: it puts the `x' and `+' side by side with no
  805. particular special results.
  806.    Keep in mind that the C preprocessor converts comments to whitespace
  807. before macros are even considered.  Therefore, you cannot create a
  808. comment by concatenating `/' and `*': the `/*' sequence that starts a
  809. comment is not a lexical unit, but rather the beginning of a "long"
  810. space character.  Also, you can freely use comments next to a `##' in a
  811. macro definition, or in actual arguments that will be concatenated,
  812. because the comments will be converted to spaces at first sight, and
  813. concatenation will later discard the spaces.
  814. File: cpp.info,  Node: Undefining,  Next: Redefining,  Prev: Concatenation,  Up: Macros
  815. Undefining Macros
  816. -----------------
  817.    To "undefine" a macro means to cancel its definition.  This is done
  818. with the `#undef' command.  `#undef' is followed by the macro name to
  819. be undefined.
  820.    Like definition, undefinition occurs at a specific point in the
  821. source file, and it applies starting from that point.  The name ceases
  822. to be a macro name, and from that point on it is treated by the
  823. preprocessor as if it had never been a macro name.
  824.    For example,
  825.      #define FOO 4
  826.      x = FOO;
  827.      #undef FOO
  828.      x = FOO;
  829. expands into
  830.      x = 4;
  831.      
  832.      x = FOO;
  833. In this example, `FOO' had better be a variable or function as well as
  834. (temporarily) a macro, in order for the result of the expansion to be
  835. valid C code.
  836.    The same form of `#undef' command will cancel definitions with
  837. arguments or definitions that don't expect arguments.  The `#undef'
  838. command has no effect when used on a name not currently defined as a
  839. macro.
  840. File: cpp.info,  Node: Redefining,  Next: Macro Pitfalls,  Prev: Undefining,  Up: Macros
  841. Redefining Macros
  842. -----------------
  843.    "Redefining" a macro means defining (with `#define') a name that is
  844. already defined as a macro.
  845.    A redefinition is trivial if the new definition is transparently
  846. identical to the old one.  You probably wouldn't deliberately write a
  847. trivial redefinition, but they can happen automatically when a header
  848. file is included more than once (*note Header Files::.), so they are
  849. accepted silently and without effect.
  850.    Nontrivial redefinition is considered likely to be an error, so it
  851. provokes a warning message from the preprocessor.  However, sometimes it
  852. is useful to change the definition of a macro in mid-compilation.  You
  853. can inhibit the warning by undefining the macro with `#undef' before the
  854. second definition.
  855.    In order for a redefinition to be trivial, the new definition must
  856. exactly match the one already in effect, with two possible exceptions:
  857.    * Whitespace may be added or deleted at the beginning or the end.
  858.    * Whitespace may be changed in the middle (but not inside strings).
  859.      However, it may not be eliminated entirely, and it may not be added
  860.      where there was no whitespace at all.
  861.    Recall that a comment counts as whitespace.
  862. File: cpp.info,  Node: Macro Pitfalls,  Prev: Redefining,  Up: Macros
  863. Pitfalls and Subtleties of Macros
  864. ---------------------------------
  865.    In this section we describe some special rules that apply to macros
  866. and macro expansion, and point out certain cases in which the rules have
  867. counterintuitive consequences that you must watch out for.
  868. * Menu:
  869. * Misnesting::        Macros can contain unmatched parentheses.
  870. * Macro Parentheses:: Why apparently superfluous parentheses
  871.                          may be necessary to avoid incorrect grouping.
  872. * Swallow Semicolon:: Macros that look like functions
  873.                          but expand into compound statements.
  874. * Side Effects::      Unsafe macros that cause trouble when
  875.                          arguments contain side effects.
  876. * Self-Reference::    Macros whose definitions use the macros' own names.
  877. * Argument Prescan::  Actual arguments are checked for macro calls
  878.                          before they are substituted.
  879. * Cascaded Macros::   Macros whose definitions use other macros.
  880. * Newlines in Args::  Sometimes line numbers get confused.
  881. File: cpp.info,  Node: Misnesting,  Next: Macro Parentheses,  Prev: Macro Pitfalls,  Up: Macro Pitfalls
  882. Improperly Nested Constructs
  883. ............................
  884.    Recall that when a macro is called with arguments, the arguments are
  885. substituted into the macro body and the result is checked, together with
  886. the rest of the input file, for more macro calls.
  887.    It is possible to piece together a macro call coming partially from
  888. the macro body and partially from the actual arguments.  For example,
  889.      #define double(x) (2*(x))
  890.      #define call_with_1(x) x(1)
  891. would expand `call_with_1 (double)' into `(2*(1))'.
  892.    Macro definitions do not have to have balanced parentheses.  By
  893. writing an unbalanced open parenthesis in a macro body, it is possible
  894. to create a macro call that begins inside the macro body but ends
  895. outside of it.  For example,
  896.      #define strange(file) fprintf (file, "%s %d",
  897.      ...
  898.      strange(stderr) p, 35)
  899. This bizarre example expands to `fprintf (stderr, "%s %d", p, 35)'!
  900. File: cpp.info,  Node: Macro Parentheses,  Next: Swallow Semicolon,  Prev: Misnesting,  Up: Macro Pitfalls
  901. Unintended Grouping of Arithmetic
  902. .................................
  903.    You may have noticed that in most of the macro definition examples
  904. shown above, each occurrence of a macro argument name had parentheses
  905. around it.  In addition, another pair of parentheses usually surround
  906. the entire macro definition.  Here is why it is best to write macros
  907. that way.
  908.    Suppose you define a macro as follows,
  909.      #define ceil_div(x, y) (x + y - 1) / y
  910. whose purpose is to divide, rounding up.  (One use for this operation is
  911. to compute how many `int' objects are needed to hold a certain number
  912. of `char' objects.)  Then suppose it is used as follows:
  913.      a = ceil_div (b & c, sizeof (int));
  914. This expands into
  915.      a = (b & c + sizeof (int) - 1) / sizeof (int);
  916. which does not do what is intended.  The operator-precedence rules of C
  917. make it equivalent to this:
  918.      a = (b & (c + sizeof (int) - 1)) / sizeof (int);
  919. But what we want is this:
  920.      a = ((b & c) + sizeof (int) - 1)) / sizeof (int);
  921. Defining the macro as
  922.      #define ceil_div(x, y) ((x) + (y) - 1) / (y)
  923. provides the desired result.
  924.    However, unintended grouping can result in another way.  Consider
  925. `sizeof ceil_div(1, 2)'.  That has the appearance of a C expression
  926. that would compute the size of the type of `ceil_div (1, 2)', but in
  927. fact it means something very different.  Here is what it expands to:
  928.      sizeof ((1) + (2) - 1) / (2)
  929. This would take the size of an integer and divide it by two.  The
  930. precedence rules have put the division outside the `sizeof' when it was
  931. intended to be inside.
  932.    Parentheses around the entire macro definition can prevent such
  933. problems.  Here, then, is the recommended way to define `ceil_div':
  934.      #define ceil_div(x, y) (((x) + (y) - 1) / (y))
  935.