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