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