|
|
1.1 root 1:
2:
3: File: cpp, Node: Top, Next: Global Actions, Up: (DIR)
4:
5: The C Preprocessor
6: ******************
7:
8: The C preprocessor is a "macro processor" that is used automatically by the
9: C compiler to transform your program before actual compilation. It is
10: called a macro processor because it allows you to define "macros", which
11: are brief abbreviations for longer constructs.
12:
13: The C preprocessor provides four separate facilities that you can use as
14: you see fit:
15:
16: * Inclusion of header files. These are files of declarations that can
17: be substituted into your program.
18:
19: * Macro expansion. You can define "macros", which are abbreviations for
20: arbitrary fragments of C code, and then the C preprocessor will
21: replace the macros with their definitions throughout the program.
22:
23: * Conditional compilation. Using special preprocessor commands, you can
24: include or exclude parts of the program according to various conditions.
25:
26: * Line control. If you use a program to combine or rearrange source
27: files into an intermediate file which is then compiled, you can use
28: line control to inform the compiler of where each source line
29: originally came from.
30:
31: C preprocessors vary in some details. This manual discusses the GNU C
32: preprocessor, the C Compatible Compiler Preprocessor. The GNU C
33: preprocessor provides a superset of the features of ANSI Standard C.
34:
35: ANSI Standard C requires the rejection of many harmless constructs commonly
36: used by today's C programs. Such incompatibility would be inconvenient for
37: users, so the GNU C preprocessor is configured to accept these constructs
38: by default. Strictly speaking, to get ANSI Standard C, you must use the
39: options `-T', `-undef' and `-pedantic', but in practice the consequences of
40: having strict ANSI Standard C make it undesirable to do this. *note
41: Invocation::.
42:
43: * Menu:
44:
45: * Global Actions:: Actions made uniformly on all input files.
46: * Commands:: General syntax of preprocessor commands.
47: * Header Files:: How and why to use header files.
48: * Macros:: How and why to use macros.
49: * Conditionals:: How and why to use conditionals.
50: * Combining Sources:: Use of line control when you combine source files.
51: * Other Commands:: Miscellaneous preprocessor commands.
52: * Output:: Format of output from the C preprocessor.
53: * Invocation:: How to invoke the preprocessor; command options.
54: * Concept Index:: Index of concepts and terms.
55: * Index:: Index of commands, predefined macros and options.
56:
57:
58:
59: File: cpp, Node: Global Actions, Next: Commands, Prev: Top, Up: Top
60:
61: Transformations Made Globally
62: =============================
63:
64: Most C preprocessor features are inactive unless you give specific commands
65: to request their use. (Preprocessor commands are lines starting with `#';
66: *Note Commands::.). But there are three transformations that the
67: preprocessor always makes on all the input it receives, even in the absence
68: of commands.
69:
70: * All C comments are replaced with single spaces.
71:
72: * Backslash-Newline sequences are deleted, no matter where. This
73: feature allows you to break long lines for cosmetic purposes without
74: changing their meaning.
75:
76: * Predefined macro names are replaced with their expansions (*Note
77: Predefined::.).
78:
79: The first two transformations are done *before* nearly all other parsing
80: and before preprocessor commands are recognized. Thus, for example, you
81: can split a line cosmetically with Backslash-Newline anywhere (except when
82: trigraphs are in use; see below).
83:
84: /*
85: */ # /*
86: */ defi\
87: ne FO\
88: O 10\
89: 20
90:
91: is equivalent into `#define FOO 1020'. You can split even an escape
92: sequence with Backslash-Newline. For example, you can split `"foo\bar"'
93: between the `\' and the `b' to get
94:
95: "foo\\
96: bar"
97:
98: This behavior is unclean: in all other contexts, a Backslash can be
99: inserted in a string constant as an ordinary character by writing a double
100: Backslash, and this creates an exception. But the ANSI C standard requires
101: it. (Strict ANSI C does not allow Newlines in string constants, so they do
102: not consider this a problem.)
103:
104: But there are a few exceptions to all three transformations.
105:
106: * C comments and predefined macro names are not recognized inside a
107: `#include' command in which the file name is delimited with `<' and `>'.
108:
109: * C comments and predefined macro names are never recognized within a
110: character or string constant. (Strictly speaking, this is the rule,
111: not an exception, but it is worth noting here anyway.)
112:
113: * Backslash-Newline may not safely be used within an ANSI ``trigraph''.
114: Trigraphs are converted before Backslash-Newline is deleted. If you
115: write what looks like a trigraph with a Backslash-Newline inside, the
116: Backslash-Newline is deleted as usual, but it is then too late to
117: recognize the trigraph.
118:
119: This exception is relevant only if you use the `-T' option to enable
120: trigraph processing. *note Invocation::.
121:
122:
123: File: cpp, Node: Commands, Next: Header Files, Prev: Global Actions, Up: Top
124:
125: Preprocessor Commands
126: =====================
127:
128: Most preprocessor features are active only if you use preprocessor commands
129: to request their use.
130:
131: Preprocessor commands are lines in your program that start with `#'. The
132: `#' is followed by an identifier that is the "command name". For example,
133: `#define' is the command that defines a macro. Whitespace is also allowed
134: before and after the `#'.
135:
136: The set of valid command names is fixed. Programs cannot define new
137: preprocessor commands.
138:
139: Some command names require arguments; these make up the rest of the command
140: line and must be separated from the command name by whitespace. For
141: example, `#define' must be followed by a macro name and the intended
142: expansion of the macro.
143:
144: A preprocessor command cannot be more than one line in normal circumstances.
145: It may be split cosmetically with Backslash-Newline, but that has no
146: effect on its meaning. Comments containing Newlines can also divide the
147: command into multiple lines, but the comments are changed to Spaces before
148: the command is interpreted. The only way a significant Newline can occur
149: in a preprocessor command is within a string constant or character
150: constant. Note that most C compilers that might be applied to the output
151: from the preprocessor do not accept string or character constants
152: containing Newlines.
153:
154: The `#' and the command name cannot come from a macro expansion. For
155: example, if `foo' is defined as a macro expanding to `define', that does
156: not make `#foo' a valid preprocessor command.
157:
158:
159: File: cpp, Node: Header Files, Next: Macros, Prev: Commands, Up: Top
160:
161: Header Files
162: ============
163:
164: A header file is a file containing C declarations and macro definitions
165: (*Note Macros::.) to be shared between several source files. You request
166: the use of a header file in your program with the C preprocessor command
167: `#include'.
168:
169:
170: File: cpp, Node: Header Uses, Next: Include Syntax, Prev: Header Files, Up: Header Files
171:
172: Uses of Header Files
173: --------------------
174:
175: Header files serve two kinds of purposes.
176:
177: * System header files declare the interfaces to parts of the operating
178: system. You include them in your program to supply the definitions
179: you need to invoke system calls and libraries.
180:
181: * Your own header files contain declarations for interfaces between the
182: source files of your program. Each time you have a group of related
183: declarations and macro definitions all or most of which are needed in
184: several different source files, it is a good idea to create a header
185: file for them.
186:
187: Including a header file produces the same results in C compilation as
188: copying the header file into each source file that needs it. But such
189: copying would be time-consuming and error-prone. With a header file, the
190: related declarations appear in only one place. If they need to be changed,
191: they can be changed in one place, and programs that include the header file
192: will automatically use the new version when next recompiled. The header
193: file eliminates the labor of finding and changing all the copies as well as
194: the risk that a failure to find one copy will result in inconsistencies
195: within a program.
196:
197: The usual convention is to give header files names that end with `.h'.
198:
199:
200: File: cpp, Node: Include Syntax, Next: Include Operation, Prev: Header Uses, Up: Header Files
201:
202: The `#include' Command
203: ----------------------
204:
205: Both user and system header files are included using the preprocessor
206: command `#include'. It has three variants:
207:
208: `#include <FILE>'
209: This variant is used for system header files. It searches for a file
210: named FILE in a list of directories specified by you, then in a
211: standard list of system directories. You specify directories to
212: search for header files with the command option `-I' (*Note
213: Invocation::.). The option `-nostdinc' inhibits searching the
214: standard system directories; in this case only the directories you
215: specify are searched.
216:
217: The parsing of this form of `#include' is slightly special because
218: comments are not recognized within the `<...>'. Thus, in `#include
219: <x/*y>' the `/*' does not start a comment and the command specifies
220: inclusion of a system header file named `x/*y'. Of course, a header
221: file with such a name is unlikely to exist on Unix, where shell
222: wildcard features would make it hard to manipulate.
223:
224: The argument FILE may not contain a `>' character. It may, however,
225: contain a `<' character.
226:
227: `#include "FILE"'
228: This variant is used for header files of your own program. It
229: searches for a file named FILE first in the current directory, then in
230: the same directories used for system header files. The current
231: directory is tried first because it is presumed to be the location of
232: the files of the program being compiled. (If the `-I-' option is
233: used, the special treatment of the current directory is inhibited.)
234:
235: The argument FILE may not contain `"' characters. If backslashes
236: occur within FILE, they are considered ordinary text characters, not
237: escape characters. None of the character escape sequences appropriate
238: to string constants in C are processed. Thus, `#include "x\n\\y"'
239: specifies a filename containing three backslashes. It is not clear
240: why this behavior is ever useful, but the ANSI standard specifies it.
241:
242: `#include ANYTHING ELSE'
243: This variant is called a "computed #include". Any `#include' command
244: whose argument does not fit the above two forms is a computed include.
245: The text ANYTHING ELSE is checked for macro calls, which are expanded
246: (*Note Macros::.). When this is done, the result must fit one of the
247: above two variants.
248:
249: This feature allows you to define a macro which controls the file name
250: to be used at a later point in the program. One application of this
251: is to allow a site-configuration file for your program to specify the
252: names of the system include files to be used. This can help in
253: porting the program to various operating systems in which the
254: necessary system header files are found in different places.
255:
256:
257: File: cpp, Node: Include Operation, Prev: Include Syntax, Up: Header Files
258:
259: How `#include' Works
260: --------------------
261:
262: The `#include' command works by directing the C preprocessor to scan the
263: specified file as input before continuing with the rest of the current
264: file. The output from the preprocessor contains the output already
265: generated, followed by the output resulting from the included file,
266: followed by the output that comes from the text after the `#include'
267: command. For example, given two files as follows:
268:
269: /* File program.c */
270: int x;
271: #include "header.h"
272:
273: main ()
274: {
275: printf (test ());
276: }
277:
278:
279: /* File header.h */
280: char *test ();
281:
282: the output generated by the C preprocessor for `program.c' as input would be
283:
284: int x;
285: char *test ();
286:
287: main ()
288: {
289: printf (test ());
290: }
291:
292: Included files are not limited to declarations and macro definitions; they
293: are merely the typical use. Any fragment of a C program can be included
294: from another file. The include file could even contain the beginning of a
295: statement that is concluded in the containing file, or the end of a
296: statement that was started in the including file. However, a comment or a
297: string or character constant may not start in the included file and finish
298: in the including file. An unterminated comment, string constant or
299: character constant in an included file is considered to end (with an error
300: message) at the end of the file.
301:
302: The line following the `#include' command is always treated as a separate
303: line by the C preprocessor even if the included file lacks a final newline.
304:
305:
306: File: cpp, Node: Macros, Next: Conditionals, Prev: Header Files, Up: Top
307:
308: Macros
309: ======
310:
311: A macro is a sort of abbreviation which you can define once and then use
312: later. There are many complicated features associated with macros in the C
313: preprocessor.
314:
315: * Menu:
316:
317: * Simple Macros:: Macros that always expand the same way.
318: * Argument Macros:: Macros that accept arguments that are substituted
319: into the macro expansion.
320: * Predefined:: Predefined macros that are always available.
321: * Stringification:: Macro arguments converted into string constants.
322: * Concatenation:: Building tokens from parts taken from macro arguments.
323: * Undefining:: Cancelling a macro's definition.
324: * Redefining:: Changing a macro's definition.
325: * Macro Pitfalls:: Macros can confuse the unwary. Here we explain
326: several common problems and strange features.
327:
328:
329:
330: File: cpp, Node: Simple Macros, Next: Argument Macros, Prev: Macros, Up: Macros
331:
332: Simple Macros
333: -------------
334:
335: A "simple macro" is a kind of abbreviation. It is a name which stands for
336: a fragment of code.
337:
338: Before you can use a macro, you must "define" it explicitly with the
339: `#define' command. `#define' is followed by the name of the macro and then
340: the code it should be an abbreviation for. For example,
341:
342: #define BUFFER_SIZE 1020
343:
344: defines a macro named `BUFFER_SIZE' as an abbreviation for the text `1020'.
345: Therefore, if somewhere after this `#define' command there comes a C
346: statement of the form
347:
348: foo = (char *) xmalloc (BUFFER_SIZE);
349:
350: then the C preprocessor will recognize and "expand" the macro
351: `BUFFER_SIZE', resulting in
352:
353: foo = (char *) xmalloc (1020);
354:
355: the definition must be a single line; however, it may not end in the middle
356: of a multi-line string constant or character constant.
357:
358: The use of all upper case for macro names is a standard convention.
359: Programs are easier to read when it is possible to tell at a glance which
360: names are macros.
361:
362: Normally, a macro definition must be a single line, like all C preprocessor
363: commands. (You can split a long macro definition cosmetically with
364: Backslash-Newline.) There is one exception: Newlines can be included in
365: the macro definition if within a string or character constant. By the same
366: token, it is not possible for a macro definition to contain an unbalanced
367: quote character; the definition automatically extends to include the
368: matching quote character that ends the string or character constant.
369: Comments within a macro definition may contain Newlines, which make no
370: difference since the comments are entirely replaced with Spaces regardless
371: of their contents.
372:
373: Aside from the above, there is no restriction on what can go in a macro
374: body. Parentheses need not balance. The body need not resemble valid C
375: code. (Of course, you might get error messages from the C compiler when
376: you use the macro.)
377:
378: The C preprocessor scans your program sequentially, so macro definitions
379: take effect at the place you write them. Therefore, the following input to
380: the C preprocessor
381:
382: foo = X;
383: #define X 4
384: bar = X;
385:
386: produces as output
387:
388: foo = X;
389:
390: bar = 4;
391:
392: After the preprocessor expands a macro name, the macro's definition body is
393: appended to the front of the remaining input, and the check for macro calls
394: continues. Therefore, the macro body can contain calls to other macros.
395: For example, after
396:
397: #define BUFSIZE 1020
398: #define TABLESIZE BUFSIZE
399:
400: the name `TABLESIZE' when used in the program would go through two stages
401: of expansion, resulting ultimately in `1020'.
402:
403: This is not at all the same as defining `TABLESIZE' to be `1020'. The
404: `#define' for `TABLESIZE' uses exactly the body you specify---in this case,
405: `BUFSIZE'---and does not check to see whether it too is the name of a
406: macro. It's only when you *use* `TABLESIZE' that the result of its
407: expansion is checked for more macro names. *note Cascaded Macros::.
408:
409:
410: File: cpp, Node: Argument Macros, Next: Predefined, Prev: Simple Macros, Up: Macros
411:
412: Macros with Arguments
413: ---------------------
414:
415: A simple macro always stands for exactly the same text, each time it is
416: used. Macros can be more flexible when they accept "arguments". Arguments
417: are fragments of code that you supply each time the macro is used. These
418: fragments are included in the expansion of the macro according to the
419: directions in the macro definition.
420:
421: To define a macro that uses arguments, you write a `#define' command with a
422: list of "argument names" in parentheses after the name of the macro. The
423: argument names may be any valid C identifiers, separated by commas and
424: optionally whitespace. The open-parenthesis must follow the macro name
425: immediately, with no space in between.
426:
427: For example, here is a macro that computes the minimum of two numeric
428: values, as it is defined in many C programs:
429:
430: #define min(X, Y) ((X) < (Y) ? (X) : (Y))
431:
432: (This is not the best way to define a ``minimum'' macro in GNU C. *note
433: Side Effects::, for more information.)
434:
435: To use a macro that expects arguments, you write the name of the macro
436: followed by a list of "actual arguments" in parentheses. separated by
437: commas. The number of actual arguments you give must match the number of
438: arguments the macro expects. Examples of use of the macro `min' include
439: `min (1, 2)' and `min (x + 28, *p)'.
440:
441: The expansion text of the macro depends on the arguments you use. Each of
442: the argument names of the macro is replaced, throughout the macro
443: definition, with the corresponding actual argument. Using the same macro
444: `min' defined above, `min (1, 2)' expands into
445:
446: ((1) < (2) ? (1) : (2))
447:
448: where `1' has been substituted for `X' and `2' for `Y'.
449:
450: Likewise, `min (x + 28, *p)' expands into
451:
452: ((x + 28) < (*p) ? (x + 28) : (*p))
453:
454: Parentheses in the actual arguments must balance; a comma within
455: parentheses does not end an argument. However, there is no requirement for
456: brackets or braces to balance; thus, if you want to supply `array[x = y, x
457: + 1]' as an argument, you must write it as `array[(x = y, x + 1)]', which
458: is equivalent C code.
459:
460: After the actual arguments are substituted into the macro body, the entire
461: result is appended to the front of the remaining input, and the check for
462: macro calls continues. Therefore, the actual arguments can contain calls
463: to other macros, either with or without arguments, or even to the same
464: macro. The macro body can also contain calls to other macros. For
465: example, `min (min (a, b), c)' expands into
466:
467: ((((a) < (b) ? (a) : (b))) < (c)
468: ? (((a) < (b) ? (a) : (b)))
469: : (c))
470:
471: (Line breaks shown here for clarity would not actually be generated.)
472:
473: If you use the macro name followed by something other than an
474: open-parenthesis (after ignoring any spaces, tabs and comments that
475: follow), it is not a call to the macro, and the preprocessor does not
476: change what you have written. Therefore, it is possible for the same name
477: to be a variable or function in your program as well as a macro, and you
478: can choose in each instance whether to refer to the macro (if an actual
479: argument list follows) or the variable or function (if an argument list
480: does not follow).
481:
482: Such dual use of one name could be confusing and should be avoided except
483: when the two meanings are effectively synonymous: that is, when the name is
484: both a macro and a function and the two have similar effects. You can
485: think of the name simply as a function; use of the name for purposes other
486: than calling it (such as, to take the address) will refer to the function,
487: while calls will expand the macro and generate better but equivalent code.
488: For example, you can use a function named `min' in the same source file
489: that defines the macro. If you write `&min' with no argument list, you
490: refer to the function. If you write `min (x, bb)', with an argument list,
491: the macro is expanded. If you write `(min) (a, bb)', where the name `min'
492: is not followed by an open-parenthesis, the macro is not expanded, so you
493: wind up with a call to the function `min'.
494:
495: It is not allowed to define the same name as both a simple macro and a
496: macro with arguments.
497:
498: In the definition of a macro with arguments, the list of argument names
499: must follow the macro name immediately with no space in between. If there
500: is a space after the macro name, the macro is defined as taking no
501: arguments, and all the rest of the name is taken to be the expansion. The
502: reason for this is that it is often useful to define a macro that takes no
503: arguments and whose definition begins with an identifier in parentheses.
504: This rule about spaces makes it possible for you to do either this:
505:
506: #define FOO(x) - 1 / (x)
507:
508: (which defines `FOO' to take an argument and expand into minus the
509: reciprocal of that argument) or this:
510:
511: #define BAR (x) - 1 / (x)
512:
513: (which defines `BAR' to take no argument and always expand into `(x) - 1 /
514: (x)').
515:
516: Note that the *uses* of a macro with arguments can have spaces before the
517: left parenthesis; it's the *definition* where it matters whether there is a
518: space.
519:
520:
521: File: cpp, Node: Predefined, Next: Stringification, Prev: Argument Macros, Up: Macros
522:
523: Predefined Macros
524: -----------------
525:
526: Several simple macros are predefined. You can use them without giving
527: definitions for them. They fall into two classes: standard macros and
528: system-specific macros.
529:
530: * Menu:
531:
532: * Standard Predefined:: Standard predefined macros.
533: * Nonstandard Predefined:: Nonstandard predefined macros.
534:
535:
536:
537: File: cpp, Node: Standard Predefined, Next: Nonstandard Predefined, Prev: Predefined, Up: Predefined
538:
539: Standard Predefined Macros
540: ..........................
541:
542: The standard predefined macros are available with the same meanings
543: regardless of the machine or operating system on which you are using GNU C.
544: Their names all start and end with double underscores. Those preceding
545: `__GNUC__' in this table are standardized by ANSI C; the rest are GNU C
546: extensions.
547:
548: `__FILE__'
549: This macro expands to the name of the current input file, in the form
550: of a C string constant.
551:
552: `__LINE__'
553: This macro expands to the current input line number, in the form of a
554: decimal integer constant. While we call it a predefined macro, it's a
555: pretty strange macro, since its ``definition'' changes with each new
556: line of source code.
557:
558: This and `__FILE__' are useful in generating an error message to
559: report an inconsistency detected by the program; the message can state
560: the source line at which the inconsistency was detected. For example,
561:
562: fprintf (stderr, "Internal error: negative string length "
563: "%d at %s, line %d.",
564: length, __FILE__, __LINE__);
565:
566: A `#include' command changes the expansions of `__FILE__' and
567: `__LINE__' to correspond to the included file. At the end of that
568: file, when processing resumes on the input file that contained the
569: `#include' command, the expansions of `__FILE__' and `__LINE__' revert
570: to the values they had before the `#include' (but `__LINE__' is then
571: incremented by one as processing moves to the line after the
572: `#include').
573:
574: The expansions of both `__FILE__' and `__LINE__' are altered if a
575: `#line' command is used. *note Combining Sources::.
576:
577: `__DATE__'
578: This macro expands to a string constant that describes the date on
579: which the preprocessor is being run. The string constant contains
580: eleven characters and looks like `"Jan 29 1987"' or `"Apr 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: `__GNUC__'
593: This macro is defined if and only if this is GNU C. This macro is
594: defined only when the entire GNU C compiler is in use; if you invoke
595: the preprocessor directly, `__GNUC__' is undefined.
596:
597: `__STRICT_ANSI__'
598: This macro is defined if and only if the `-ansi' switch was specified
599: when GNU C was invoked. Its definition is the null string. This
600: macro exists primarily to direct certain GNU header files not to
601: define certain traditional Unix constructs which are incompatible with
602: ANSI C.
603:
604: `__VERSION__'
605: This macro expands to a string which describes the version number of
606: GNU C. The string is normally a sequence of decimal numbers separated
607: by periods, such as `"1.18"'. The only reasonable use of this macro
608: is to incorporate it into a string constant.
609:
610: `__OPTIMIZE__'
611: This macro is defined in optimizing compilations. It causes certain
612: GNU header files to define alternative macro definitions for some
613: system library functions. It is unwise to refer to or test the
614: definition of this macro unless you make very sure that programs will
615: execute with the same effect regardless.
616:
617: `__CHAR_UNSIGNED__'
618: This macro is defined if and only if the data type `char' is unsigned
619: on the target machine. It exists to cause the standard header file
620: `limit.h' to work correctly. It is bad practice to refer to this
621: macro yourself; instead, refer to the standard macros defined in
622: `limit.h'.
623:
624:
625: File: cpp, Node: Nonstandard Predefined, Prev: Standard Predefined, Up: Predefined
626:
627: Nonstandard Predefined Macros
628: .............................
629:
630: The C preprocessor normally has several predefined macros that vary between
631: machines because their purpose is to indicate what type of system and
632: machine is in use. This manual, being for all systems and machines, cannot
633: tell you exactly what their names are; instead, we offer a list of some
634: typical ones.
635:
636: Some nonstandard predefined macros describe the operating system in use,
637: with more or less specificity. For example,
638:
639: `unix'
640: `unix' is normally predefined on all Unix systems.
641:
642: `BSD'
643: `BSD' is predefined on recent versions of Berkeley Unix (perhaps only
644: in version 4.3).
645:
646: Other nonstandard predefined macros describe the kind of CPU, with more or
647: less specificity. For example,
648:
649: `vax'
650: `vax' is predefined on Vax computers.
651:
652: `mc68000'
653: `mc68000' is predefined on most computers whose CPU is a Motorola
654: 68000, 68010 or 68020.
655:
656: `m68k'
657: `m68k' is also predefined on most computers whose CPU is a 68000,
658: 68010 or 68020; however, some makers use `mc68000' and some use
659: `m68k'. Some predefine both names. What happens in GNU C depends on
660: the system you are using it on.
661:
662: `M68020'
663: `M68020' has been observed to be predefined on some systems that use
664: 68020 CPUs---in addition to `mc68000' and `m68k' that are less specific.
665:
666: `ns32000'
667: `ns32000' is predefined on computers which use the National
668: Semiconductor 32000 series CPU.
669:
670: Yet other nonstandard predefined macros describe the manufacturer of the
671: system. For example,
672:
673: `sun'
674: `sun' is predefined on all models of Sun computers.
675:
676: `pyr'
677: `pyr' is predefined on all models of Pyramid computers.
678:
679: `sequent'
680: `sequent' is predefined on all models of Sequent computers.
681:
682: These predefined symbols are not only nonstandard, they are contrary to the
683: ANSI standard because their names do not start with underscores. However,
684: the GNU C preprocessor would be useless if it did not predefine the same
685: names that are normally predefined on the system and machine you are using.
686: Even system header files check the predefined names and will generate
687: incorrect declarations if they do not find the names that are expected.
688:
689: The set of nonstandard predefined names in the GNU C preprocessor is
690: controlled by the macro `CPP_PREDEFINES', which should be a string
691: containing `-D' options, separated by spaces. For example, on the Sun, the
692: definition
693:
694: #define CPP_PREDEFINES "-Dmc68000 -Dsun -Dunix -Dm68k"
695:
696: is used.
697:
698: The `-ansi' option which requests complete support for ANSI C inhibits the
699: definition of these predefined symbols.
700:
701:
702: File: cpp, Node: Stringification, Next: Concatenation, Prev: Predefined, Up: Macros
703:
704: Stringification
705: ---------------
706:
707: "Stringification" means turning a code fragment into a string constant
708: whose contents are the text for the code fragment. For example,
709: stringifying `foo (z)' results in `"foo (z)"'.
710:
711: In the C preprocessor, stringification is an option available when macro
712: arguments are substituted into the macro definition. In the body of the
713: definition, when an argument name appears, the character `#' before the
714: name specifies stringification of the corresponding actual argument when it
715: is substituted at that point in the definition. The same argument may be
716: substituted in other places in the definition without stringification if
717: the argument name appears in those places with no `#'.
718:
719: Here is an example of a macro definition that uses stringification:
720:
721: #define WARN_IF(EXP) \
722: do { if (EXP) fprintf (stderr, "Warning: " #EXP "\n"); } while (0)
723:
724: Here the actual argument for `EXP' is substituted once as given, into the
725: `if' statement, and once as stringified, into the argument to `fprintf'.
726: The `do' and `while (0)' are a kludge to make it possible to write `WARN_IF
727: (ARG);', which the resemblance of `WARN_IF' to a function would make C
728: programmers want to do; *Note Swallow Semicolon::.).
729:
730: The stringification feature is limited to transforming one macro argument
731: into one string constant: there is no way to combine the argument with
732: other text and then stringify it all together. But the example above shows
733: how an equivalent result can be obtained in ANSI Standard C using the
734: feature that adjacent string constants are concatenated as one string
735: constant. The preprocessor stringifies `EXP''s actual argument into a
736: separate string constant, resulting in text like
737:
738: do { if (x == 0) fprintf (stderr, "Warning: " "x == 0" "\n"); } while (0)
739:
740: but the C compiler then sees three consecutive string constants and
741: concatenates them into one, producing effectively
742:
743: do { if (x == 0) fprintf (stderr, "Warning: x == 0\n"); } while (0)
744:
745: Stringification in C involves more than putting doublequote characters
746: around the fragment; it is necessary to put backslashes in front of all
747: doublequote characters, and all backslashes in string and character
748: constants, in order to get a valid C string constant with the proper
749: contents. Thus, stringifying `p = "foo\n";' results in `"p =
750: \"foo\\n\";"'. However, backslashes that are not inside of string or
751: character constants are not duplicated: `\n' by itself stringifies to `"\n"'.
752:
753: Whitespace (including comments) in the text being stringified is handled
754: according to precise rules. All leading and trailing whitespace is ignored.
755: Any sequence of whitespace in the middle of the text is converted to a
756: single space in the stringified result.
757:
758:
759: File: cpp, Node: Concatenation, Next: Undefining, Prev: Stringification, Up: Macros
760:
761: Concatenation
762: -------------
763:
764: "Concatenation" means joining two strings into one. In the context of
765: macro expansion, concatenation refers to joining two lexical units into one
766: longer one. Specifically, an actual argument to the macro can be
767: concatenated with another actual argument or with fixed text to produce a
768: longer name. The longer name might be the name of a function, variable or
769: type, or a C keyword; it might even be the name of another macro, in which
770: case it will be expanded.
771:
772: When you define a macro, you request concatenation with the special
773: operator `##' in the macro body. When the macro is called, after actual
774: arguments are substituted, all `##' operators are deleted, and so is any
775: whitespace next to them (including whitespace that was part of an actual
776: argument). The result is to concatenate the syntactic tokens on either
777: side of the `##'.
778:
779: Consider a C program that interprets named commands. There probably needs
780: to be a table of commands, perhaps an array of structures declared as
781: follows:
782:
783: struct command
784: {
785: char *name;
786: void (*function) ();
787: };
788:
789: struct command commands[] =
790: {
791: { "quit", quit_command},
792: { "help", help_command},
793: ...
794: };
795:
796: It would be cleaner not to have to give each command name twice, once in
797: the string constant and once in the function name. A macro which takes the
798: name of a command as an argument can make this unnecessary. The string
799: constant can be created with stringification, and the function name by
800: concatenating the argument with `_command'. Here is how it is done:
801:
802: #define COMMAND(NAME) { #NAME, NAME ## _command }
803:
804: struct command commands[] =
805: {
806: COMMAND (quit),
807: COMMAND (help),
808: ...
809: };
810:
811: The usual case of concatenation is concatenating two names (or a name and a
812: number) into a longer name. But this isn't the only valid case. It is
813: also possible to concatenate two numbers (or a number and a name, such as
814: `1.5' and `e3') into a number. Also, multi-character operators such as
815: `+=' can be formed by concatenation. In some cases it is even possible to
816: piece together a string constant. However, two pieces of text that don't
817: together form a valid lexical unit cannot be concatenated. For example,
818: concatenation with `x' on one side and `+' on the other is not meaningful
819: because those two characters can't fit together in any lexical unit of C.
820: The ANSI standard says that such attempts at concatenation are undefined,
821: but in the GNU C preprocessor it is well defined: it puts the `x' and `+'
822: side by side with no particular special results.
823:
824: Keep in mind that the C preprocessor converts comments to whitespace before
825: macros are even considered. Therefore, you cannot create a comment by
826: concatenating `/' and `*': the `/*' sequence that starts a comment is not a
827: lexical unit, but rather the beginning of a ``long'' space character.
828: Also, you can freely use comments next to a `##' in a macro definition, or
829: in actual arguments that will be concatenated, because the comments will be
830: converted to spaces at first sight, and concatenation will later discard
831: the spaces.
832:
833:
834: File: cpp, Node: Undefining, Next: Redefining, Prev: Concatenation, Up: Macros
835:
836: Undefining Macros
837: -----------------
838:
839: To "undefine" a macro means to cancel its definition. This is done with
840: the `#undef' command. `#undef' is followed by the macro name to be
841: undefined.
842:
843: Like definition, undefinition occurs at a specific point in the source
844: file, and it applies starting from that point. The name ceases to be a
845: macro name, and from that point on it is treated by the preprocessor as if
846: it had never been a macro name.
847:
848: For example,
849:
850: #define FOO 4
851: x = FOO;
852: #undef FOO
853: x = FOO;
854:
855: expands into
856:
857: x = 4;
858:
859: x = FOO;
860:
861: In this example, `FOO' had better be a variable or function as well as
862: (temporarily) a macro, in order for the result of the expansion to be valid
863: C code.
864:
865: The same form of `#undef' command will cancel definitions with arguments or
866: definitions that don't expect arguments. The `#undef' command has no
867: effect when used on a name not currently defined as a macro.
868:
869:
870: File: cpp, Node: Redefining, Next: Macro Pitfalls, Prev: Undefining, Up: Macros
871:
872: Redefining Macros
873: -----------------
874:
875: "Redefining" a macro means defining (with `#define') a name that is already
876: defined as a macro.
877:
878: A redefinition is trivial if the new definition is transparently identical
879: to the old one. You probably wouldn't deliberately write a trivial
880: redefinition, but they can happen automatically when a header file is
881: included more than once (*Note Header Files::.), so they are accepted
882: silently and without effect.
883:
884: Nontrivial redefinition is considered likely to be an error, so it provokes
885: a warning message from the preprocessor. However, sometimes it is useful
886: to change the definition of a macro in mid-compilation. You can inhibit
887: the warning by undefining the macro with `#undef' before the second
888: definition.
889:
890: In order for a reefinition to be trivial, the new definition must exactly
891: match the one already in effect, with two possible exceptions:
892:
893: * Whitespace may be added or deleted at the beginning or the end.
894:
895: * Whitespace may be changed in the middle (but not inside strings).
896: However, it may not be eliminated entirely, and it may not be added
897: where there was no whitespace at all.
898:
899: Recall that a comment counts as whitespace.
900:
901:
902: File: cpp, Node: Macro Pitfalls, Prev: Redefining, Up: Macros
903:
904: Pitfalls and Subtleties of Macros
905: ---------------------------------
906:
907: In this section we describe some special rules that apply to macros and
908: macro expansion, and point out certain cases in which the rules have
909: counterintuitive consequences that you must watch out for.
910:
911: * Menu:
912:
913: * Misnesting:: Macros can contain unmatched parentheses.
914: * Macro Parentheses:: Why apparently superfluous parentheses
915: may be necessary to avoid incorrect grouping.
916: * Swallow Semicolon:: Macros that look like functions
917: but expand into compound statements.
918: * Side Effects:: Unsafe macros that cause trouble when
919: arguments contain side effects.
920: * Self-Reference:: Macros whose definitions use the macros' own names.
921: * Argument Prescan:: Actual arguments are checked for macro calls
922: before they are substituted.
923: * Cascaded Macros:: Macros whose definitions use other macros.
924:
925:
926:
927: File: cpp, Node: Misnesting, Next: Macro Parentheses, Prev: Macro Pitfalls, Up: Macro Pitfalls
928:
929: Improperly Nested Constructs
930: ............................
931:
932: Recall that when a macro is called with arguments, the arguments are
933: substituted into the macro body and the result is checked, together with
934: the rest of the input file, for more macro calls.
935:
936: It is possible to piece together a macro call coming partially from the
937: macro body and partially from the actual arguments. For example,
938:
939: #define double(x) (2*(x))
940: #define call_with_1(x) x(1)
941:
942: would expand `call_with_1 (double)' into `(2*(1))'.
943:
944: Macro definitions do not have to have balanced parentheses. By writing an
945: unbalanced open parenthesis in a macro body, it is possible to create a
946: macro call that begins inside the macro body but ends outside of it. For
947: example,
948:
949: #define strange(file) fprintf (file, "%s %d",
950: ...
951: strange(stderr) p, 35)
952:
953: This bizarre example expands to `fprintf (stderr, "%s %d", p, 35)'!
954:
955:
956: File: cpp, Node: Macro Parentheses, Next: Swallow Semicolon, Prev: Misnesting, Up: Macro Pitfalls
957:
958: Unintended Grouping of Arithmetic
959: .................................
960:
961: You may have noticed that in most of the macro definition examples shown
962: above, each occurrence of a macro argument name had parentheses around it.
963: In addition, another pair of parentheses usually surround the entire macro
964: definition. Here is why it is best to write macros that way.
965:
966: Suppose you define a macro as follows
967:
968: #define ceil_div(x, y) (x + y - 1) / y
969:
970: whose purpose is to divide, rounding up. (One use for this operation is to
971: compute how many `int''s are needed to hold a certain number of `char''s.)
972: Then suppose it is used as follows:
973:
974: a = ceil_div (b & c, sizeof (int));
975:
976: This expands into
977:
978: a = (b & c + sizeof (int) - 1) / sizeof (int);
979:
980: which does not do what is intended. The operator-precedence rules of C
981: make it equivalent to this:
982:
983: a = (b & (c + sizeof (int) - 1)) / sizeof (int);
984:
985: But what we want is this:
986:
987: a = ((b & c) + sizeof (int) - 1)) / sizeof (int);
988:
989: Defining the macro as
990:
991: #define ceil_div(x, y) ((x) + (y) - 1) / (y)
992:
993: provides the desired result.
994:
995: However, unintended grouping can result in another way. Consider `sizeof
996: ceil_div(1, 2)'. That has the appearance of a C expression that would
997: compute the size of the type of `ceil_div (1, 2)', but in fact it means
998: something very different. Here is what it expands to:
999:
1000: sizeof ((1) + (2) - 1) / (2)
1001:
1002: This would take the size of an integer and divide it by two. The
1003: precedence rules have put the division outside the `sizeof' when it was
1004: intended to be inside.
1005:
1006: Parentheses around the entire macro definition can prevent such problems.
1007: Here, then, is the recommended way to define `ceil_div':
1008:
1009: #define ceil_div(x, y) (((x) + (y) - 1) / (y))
1010:
1011:
1012: File: cpp, Node: Swallow Semicolon, Next: Side Effects, Prev: Macro Parentheses, Up: Macro Pitfalls
1013:
1014: Swallowing the Semicolon
1015: ........................
1016:
1017: Often it is desirable to define a macro that expands into a compound
1018: statement. Consider, for example, the following macro, that advances a
1019: pointer (the argument `p' says where to find it) across whitespace
1020: characters:
1021:
1022: #define SKIP_SPACES (p, limit) \
1023: { register char *lim = (limit); \
1024: while (p != lim) { \
1025: if (*p++ != ' ') { \
1026: p--; break; }}}
1027:
1028: Here Backslash-Newline is used to split the macro definition, which must be
1029: a single line, so that it resembles the way such C code would be layed out
1030: if not part of a macro definition.
1031:
1032: A call to this macro might be `SKIP_SPACES (p, lim)'. Strictly speaking,
1033: the call expands to a compound statement, which is a complete statement
1034: with no need for a semicolon to end it. But it looks like a function call.
1035: So it minimizes confusion if you can use it like a function call, writing
1036: a semicolon afterward, as in `SKIP_SPACES (p, lim);'
1037:
1038: But this can cause trouble before `else' statements, because the semicolon
1039: is actually a null statement. Suppose you write
1040:
1041: if (*p != 0)
1042: SKIP_SPACES (p, lim);
1043: else ...
1044:
1045: The presence of two statements---the compound statement and a null
1046: statement---in between the `if' condition and the `else' makes invalid C
1047: code.
1048:
1049: The definition of the macro `SKIP_SPACES' can be altered to solve this
1050: problem, using a `do ... while' statement. Here is how:
1051:
1052: #define SKIP_SPACES (p, limit) \
1053: do { register char *lim = (limit); \
1054: while (p != lim) { \
1055: if (*p++ != ' ') { \
1056: p--; break; }}} \
1057: while (0)
1058:
1059: Now `SKIP_SPACES (p, lim);' expands into
1060:
1061: do {...} while (0);
1062:
1063: which is one statement.
1064:
1065:
1066: File: cpp, Node: Side Effects, Next: Self-Reference, Prev: Swallow Semicolon, Up: Macro Pitfalls
1067:
1068: Duplication of Side Effects
1069: ...........................
1070:
1071: Many C programs define a macro `min', for ``minimum'', like this:
1072:
1073: #define min(X, Y) ((X) < (Y) ? (X) : (Y))
1074:
1075: When you use this macro with an argument containing a side effect, as shown
1076: here,
1077:
1078: next = min (x + y, foo (z));
1079:
1080: it expands as follows:
1081:
1082: next = ((x + y) < (foo (z)) ? (x + y) : (foo (z)));
1083:
1084: where `x + y' has been substituted for `X' and `foo (z)' for `Y'.
1085:
1086: The function `foo' is used only once in the statement as it appears in the
1087: program, but the expression `foo (z)' has been substituted twice into the
1088: macro expansion. As a result, `foo' might be called two times when the
1089: statement is executed. If it has side effects or if it takes a long time
1090: to compute, the results might not be what you intended. We say that `min'
1091: is an "unsafe" macro.
1092:
1093: The best solution to this problem is to define `min' in a way that computes
1094: the value of `foo (z)' only once. The C language offers no way standard
1095: way to do this, but it can be done with GNU C extensions as follows:
1096:
1097: #define min(X, Y) \
1098: ({ typeof (X) __x = (X), __y = (Y); \
1099: (__x < __y) ? __x : __y; })
1100:
1101: If you do not wish to use GNU C extensions, the only solution is to be
1102: careful when *using* the macro `min'. For example, you can calculate the
1103: value of `foo (z)', save it in a variable, and use that variable in `min':
1104:
1105: #define min(X, Y) ((X) < (Y) ? (X) : (Y))
1106: ...
1107: {
1108: int tem = foo (z);
1109: next = min (x + y, tem);
1110: }
1111:
1112: (where I assume that `foo' returns type `int').
1113:
1114:
1115: File: cpp, Node: Self-Reference, Next: Argument Prescan, Prev: Side Effects, Up: Macro Pitfalls
1116:
1117: Self-Referential Macros
1118: .......................
1119:
1120: A "self-referential" macro is one whose name appears in its definition. A
1121: special feature of ANSI Standard C is that the self-reference is not
1122: considered a macro call. It is passed into the preprocessor output
1123: unchanged.
1124:
1125: Let's consider an example:
1126:
1127: #define foo (4 + foo)
1128:
1129: where `foo' is also a variable in your program.
1130:
1131: Following the ordinary rules, each reference to `foo' will expand into `(4
1132: + foo)'; then this will be rescanned and will expand into `(4 + (4 +
1133: foo))'; and so on until it causes a fatal error (memory full) in the
1134: preprocessor.
1135:
1136: However, the special rule about self-reference cuts this process short
1137: after one step, at `(4 + foo)'. Therefore, this macro definition has the
1138: possibly useful effect of causing the program to add 4 to the value of
1139: `foo' wherever `foo' is referred to.
1140:
1141: In most cases, it is a bad idea to take advantage of this feature. A
1142: person reading the program who sees that `foo' is a variable will not
1143: expect that it is a macro as well. The reader will come across a the
1144: identifier `foo' in the program and think its value should be that of the
1145: variable `foo', whereas in fact the value is four greater.
1146:
1147: The special rule for self-reference applies also to "indirect"
1148: self-reference. This is the case where a macro X expands to use a macro
1149: `y', and `y''s expansion refers to the macro `x'. The resulting reference
1150: to `x' comes indirectly from the expansion of `x', so it is a
1151: self-reference and is not further expanded. Thus, after
1152:
1153: #define x (4 + y)
1154: #define y (2 * x)
1155:
1156: `x' would expand into `(4 + (2 * x))'. Clear?
1157:
1158: But suppose `y' is used elsewhere, not from the definition of `x'. Then
1159: the use of `x' in the expansion of `y' is not a self-reference because `x'
1160: is not ``in progress''. So it does expand. However, the expansion of `x'
1161: contains a reference to `y', and that is an indirect self-reference now
1162: because `y' is ``in progress''. The result is that `y' expands to `(2 * (4
1163: + y))'.
1164:
1165: It is not clear that this behavior would ever be useful, but it is
1166: specified by the ANSI C standard, so you need to understand it.
1167:
1168:
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.