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