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