📄 cpp.texi
字号:
CPU family.@item ns32000@findex ns32000@samp{ns32000} is predefined on computers which use the NationalSemiconductor 32000 series CPU.@end tableYet other nonstandard predefined macros describe the manufacturer ofthe system. For example,@table @code@item sun@findex sun@samp{sun} is predefined on all models of Sun computers.@item pyr@findex pyr@samp{pyr} is predefined on all models of Pyramid computers.@item sequent@findex sequent@samp{sequent} is predefined on all models of Sequent computers.@end tableThese predefined symbols are not only nonstandard, they are contrary to theANSI standard because their names do not start with underscores.Therefore, the option @samp{-ansi} inhibits the definition of thesesymbols.This tends to make @samp{-ansi} useless, since many programs depend on thecustomary nonstandard predefined symbols. Even system header files checkthem and will generate incorrect declarations if they do not find the namesthat are expected. You might think that the header files supplied for theUglix computer would not need to test what machine they are running on,because they can simply assume it is the Uglix; but often they do, and theydo so using the customary names. As a result, very few C programs willcompile with @samp{-ansi}. We intend to avoid such problems on the GNUsystem.What, then, should you do in an ANSI C program to test the type of machineit will run on?GNU C offers a parallel series of symbols for this purpose, whose namesare made from the customary ones by adding @samp{__} at the beginningand end. Thus, the symbol @code{__vax__} would be available on a Vax,and so on.The set of nonstandard predefined names in the GNU C preprocessor iscontrolled (when @code{cpp} is itself compiled) by the macro@samp{CPP_PREDEFINES}, which should be a string containing @samp{-D}options, separated by spaces. For example, on the Sun 3, we use thefollowing definition:@example#define CPP_PREDEFINES "-Dmc68000 -Dsun -Dunix -Dm68k"@end example@noindent This macro is usually specified in @file{tm.h}.@node Stringification, Concatenation, Predefined, Macros@subsection Stringification@cindex stringification@dfn{Stringification} means turning a code fragment into a string constantwhose contents are the text for the code fragment. For example,stringifying @samp{foo (z)} results in @samp{"foo (z)"}.In the C preprocessor, stringification is an option available when macroarguments are substituted into the macro definition. In the body of thedefinition, when an argument name appears, the character @samp{#} beforethe name specifies stringification of the corresponding actual argumentwhen it is substituted at that point in the definition. The same argumentmay be substituted in other places in the definition withoutstringification if the argument name appears in those places with no@samp{#}.Here is an example of a macro definition that uses stringification:@smallexample@group#define WARN_IF(EXP) \do @{ if (EXP) \ fprintf (stderr, "Warning: " #EXP "\n"); @} \while (0)@end group@end smallexample@noindentHere the actual argument for @samp{EXP} is substituted once as given,into the @samp{if} statement, and once as stringified, into theargument to @samp{fprintf}. The @samp{do} and @samp{while (0)} area kludge to make it possible to write @samp{WARN_IF (@var{arg});},which the resemblance of @samp{WARN_IF} to a function would makeC programmers want to do; see @ref{Swallow Semicolon}.The stringification feature is limited to transforming one macro argumentinto one string constant: there is no way to combine the argument withother text and then stringify it all together. But the example above showshow an equivalent result can be obtained in ANSI Standard C using thefeature that adjacent string constants are concatenated as one stringconstant. The preprocessor stringifies the actual value of @samp{EXP} into a separate string constant, resulting in text like@smallexample@groupdo @{ if (x == 0) \ fprintf (stderr, "Warning: " "x == 0" "\n"); @} \while (0)@end group@end smallexample@noindentbut the C compiler then sees three consecutive string constants andconcatenates them into one, producing effectively@smallexampledo @{ if (x == 0) \ fprintf (stderr, "Warning: x == 0\n"); @} \while (0)@end smallexampleStringification in C involves more than putting doublequote charactersaround the fragment; it is necessary to put backslashes in front of alldoublequote characters, and all backslashes in string and characterconstants, in order to get a valid C string constant with the propercontents. Thus, stringifying @samp{p = "foo\n";} results in @samp{"p =\"foo\\n\";"}. However, backslashes that are not inside of string orcharacter constants are not duplicated: @samp{\n} by itself stringifies to@samp{"\n"}.Whitespace (including comments) in the text being stringified is handledaccording to precise rules. All leading and trailing whitespace is ignored.Any sequence of whitespace in the middle of the text is converted toa single space in the stringified result.@node Concatenation, Undefining, Stringification, Macros@subsection Concatenation@cindex concatenation@cindex @samp{##}@dfn{Concatenation} means joining two strings into one. In the contextof macro expansion, concatenation refers to joining two lexical unitsinto one longer one. Specifically, an actual argument to the macro can beconcatenated with another actual argument or with fixed text to producea longer name. The longer name might be the name of a function,variable or type, or a C keyword; it might even be the name of anothermacro, in which case it will be expanded.When you define a macro, you request concatenation with the specialoperator @samp{##} in the macro body. When the macro is called,after actual arguments are substituted, all @samp{##} operators aredeleted, and so is any whitespace next to them (including whitespacethat was part of an actual argument). The result is to concatenatethe syntactic tokens on either side of the @samp{##}.Consider a C program that interprets named commands. There probably needsto be a table of commands, perhaps an array of structures declared asfollows:@examplestruct command@{ char *name; void (*function) ();@};struct command commands[] =@{ @{ "quit", quit_command@}, @{ "help", help_command@}, @dots{}@};@end exampleIt would be cleaner not to have to give each command name twice, once inthe string constant and once in the function name. A macro which takes thename of a command as an argument can make this unnecessary. The stringconstant can be created with stringification, and the function name byconcatenating the argument with @samp{_command}. Here is how it is done:@example#define COMMAND(NAME) @{ #NAME, NAME ## _command @}struct command commands[] =@{ COMMAND (quit), COMMAND (help), @dots{}@};@end exampleThe usual case of concatenation is concatenating two names (or a name and anumber) into a longer name. But this isn't the only valid case. It isalso possible to concatenate two numbers (or a number and a name, such as@samp{1.5} and @samp{e3}) into a number. Also, multi-character operatorssuch as @samp{+=} can be formed by concatenation. In some cases it is evenpossible to piece together a string constant. However, two pieces of textthat don't together form a valid lexical unit cannot be concatenated. Forexample, concatenation with @samp{x} on one side and @samp{+} on the otheris not meaningful because those two characters can't fit together in anylexical unit of C. The ANSI standard says that such attempts atconcatenation are undefined, but in the GNU C preprocessor it is welldefined: it puts the @samp{x} and @samp{+} side by side with no particularspecial results.Keep in mind that the C preprocessor converts comments to whitespace beforemacros are even considered. Therefore, you cannot create a comment byconcatenating @samp{/} and @samp{*}: the @samp{/*} sequence that starts acomment is not a lexical unit, but rather the beginning of a ``long'' spacecharacter. Also, you can freely use comments next to a @samp{##} in amacro definition, or in actual arguments that will be concatenated, becausethe comments will be converted to spaces at first sight, and concatenationwill later discard the spaces.@node Undefining, Redefining, Concatenation, Macros@subsection Undefining Macros@cindex undefining macrosTo @dfn{undefine} a macro means to cancel its definition. This is donewith the @samp{#undef} directive. @samp{#undef} is followed by the macroname to be undefined.Like definition, undefinition occurs at a specific point in the sourcefile, and it applies starting from that point. The name ceases to be amacro name, and from that point on it is treated by the preprocessor as ifit had never been a macro name.For example,@example#define FOO 4x = FOO;#undef FOOx = FOO;@end example@noindentexpands into@examplex = 4;x = FOO;@end example@noindentIn this example, @samp{FOO} had better be a variable or function as wellas (temporarily) a macro, in order for the result of the expansion to bevalid C code.The same form of @samp{#undef} directive will cancel definitions witharguments or definitions that don't expect arguments. The @samp{#undef}directive has no effect when used on a name not currently defined as a macro.@node Redefining, Macro Pitfalls, Undefining, Macros@subsection Redefining Macros@cindex redefining macros@dfn{Redefining} a macro means defining (with @samp{#define}) a name thatis already defined as a macro.A redefinition is trivial if the new definition is transparently identicalto the old one. You probably wouldn't deliberately write a trivialredefinition, but they can happen automatically when a header file isincluded more than once (@pxref{Header Files}), so they are acceptedsilently and without effect.Nontrivial redefinition is considered likely to be an error, soit provokes a warning message from the preprocessor. However, sometimes itis useful to change the definition of a macro in mid-compilation. You caninhibit the warning by undefining the macro with @samp{#undef} before thesecond definition.In order for a redefinition to be trivial, the new definition mustexactly match the one already in effect, with two possible exceptions:@itemize @bullet@itemWhitespace may be added or deleted at the beginning or the end.@itemWhitespace may be changed in the middle (but not inside strings).However, it may not be eliminated entirely, and it may not be addedwhere there was no whitespace at all.@end itemizeRecall that a comment counts as whitespace.@node Macro Pitfalls,, Redefining, Macros@subsection Pitfalls and Subtleties of Macros@cindex problems with macros@cindex pitfalls of macrosIn this section we describe some special rules that apply to macros andmacro expansion, and point out certain cases in which the rules havecounterintuitive consequences that you must watch out for.@menu* Misnesting:: Macros can contain unmatched parentheses.* Macro Parentheses:: Why apparently superfluous parentheses may be necessary to avoid incorrect grouping.* Swallow Semicolon:: Macros that look like functions but expand into compound statements.* Side Effects:: Unsafe macros that cause trouble when arguments contain side effects.* Self-Reference:: Macros whose definitions use the macros' own names.* Argument Prescan:: Actual arguments are checked for macro calls before they are substituted.* Cascaded Macros:: Macros whose definitions use other macros.* Newlines in Args:: Sometimes line numbers get confused.@end menu@node Misnesting, Macro Parentheses, Macro Pitfalls, Macro Pitfalls@subsubsection Improperly Nested ConstructsRecall that when a macro is called with arguments, the arguments aresubstituted into the macro body and the result is checked, together withthe rest of the input file, for more macro calls.It is possible to piece together a macro call coming partially from themacro body and partially from the actual arguments. For example,@example#define double(x) (2*(x))#define call_with_1(x) x(1)@end example@noindentwould expand @samp{call_with_1 (double)} into @samp{(2*(1))}.Macro definitions do not have to have balanced parentheses. By writing anunbalanced open parenthesis in a macro body, it is possible to create amacro call that begins inside the macro body but ends outside of it. Forexample,@example#define strange(file) fprintf (file, "%s %d",@dots{}strange(stderr) p, 35)@end example@noindentThis bizarre example expands to @samp{fprintf (stderr, "%s %d", p, 35)}!@node Macro Parentheses, Swallow Semicolon, Misnesting, Macro Pitfalls
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -