📄 cpp.texi
字号:
@node Include Operation, Once-Only, Include Syntax, Header Files@subsection How @samp{#include} WorksThe @samp{#include} command works by directing the C preprocessor to scanthe specified file as input before continuing with the rest of the currentfile. The output from the preprocessor contains the output alreadygenerated, followed by the output resulting from the included file,followed by the output that comes from the text after the @samp{#include}command. For example, given two files as follows:@example/* File program.c */int x;#include "header.h"main ()@{ printf (test ());@}/* File header.h */char *test ();@end example@noindentthe output generated by the C preprocessor for @file{program.c} as inputwould be@exampleint x;char *test ();main ()@{ printf (test ());@}@end exampleIncluded files are not limited to declarations and macro definitions; thoseare merely the typical uses. Any fragment of a C program can be includedfrom another file. The include file could even contain the beginning of astatement that is concluded in the containing file, or the end of astatement that was started in the including file. However, a comment or astring or character constant may not start in the included file and finishin the including file. An unterminated comment, string constant orcharacter constant in an included file is considered to end (with an errormessage) at the end of the file.The line following the @samp{#include} command is always treated as aseparate line by the C preprocessor even if the included file lacks a finalnewline.@node Once-Only, Inheritance, Include Operation, Header Files@subsection Once-Only Include Files@cindex repeated inclusionVery often, one header file includes another. It can easily result that acertain header file is included more than once. This may lead to errors,if the header file defines structure types or typedefs, and is certainlywasteful. Therefore, we often wish to prevent multiple inclusion of aheader file.The standard way to do this is to enclose the entire real contents of thefile in a conditional, like this:@example#ifndef __FILE_FOO_SEEN__#define __FILE_FOO_SEEN__@var{the entire file}#endif /* __FILE_FOO_SEEN__ */@end exampleThe macro @code{__FILE_FOO_SEEN__} indicates that the file has beenincluded once already; its name should begin with @samp{__} to avoidconflicts with user programs, and it should contain the name of the fileand some additional text, to avoid conflicts with other header files.The GNU C preprocessor is programmed to notice when a header file usesthis particular construct and handle it efficiently. If a header fileis contained entirely in a @samp{#ifndef} conditional, then it recordsthat fact. If a subsequent @samp{#include} specifies the same file,and the macro in the @samp{#ifndef} is already defined, then the fileis entirely skipped, without even reading it.@findex #pragma onceThere is also an explicit command to tell the preprocessor that it neednot include a file more than once. This is called @samp{#pragma once},and was used @emph{in addition to} the @samp{#ifndef} conditional aroundthe contents of the header file. @samp{#pragma once} is now obsoleteand should not be used at all.In the Objective C language, there is a variant of @samp{#include}called @samp{#import} which includes a file, but does so at most once.If you use @samp{#import} @emph{instead of} @samp{#include}, then youdon't need the conditionals inside the header file to prevent multipleexecution of the contents.@samp{#import} is obsolete because it is not a well-designed feature.It requires the users of a header file---the applicationsprogrammers---to know that a certain header file should only be includedonce. It is much better for the header file's implementor to write thefile so that users don't need to know this. Using @samp{#ifndef}accomplishes this goal.@node Inheritance,, Once-Only, Header Files@section Inheritance and Header Files@cindex inheritance@cindex overriding a header file@dfn{Inheritance} is what happens when one object or file derives someof its contents by virtual copying from another object or file. Inthe case of C header files, inheritance means that one header file includes another header file and then replaces or adds something.If the inheriting header file and the base header file have differentnames, then inheritance is straightforward: simply write @samp{#include"@var{base}"} in the inheriting file.Sometimes it is necessary to give the inheriting file the same name asthe base file. This is less straightforward.For example, suppose an application program uses the system header file@file{sys/signal.h}, but the version of @file{/usr/include/sys/signal.h}on a particular system doesn't do what the application program expects.It might be convenient to define a ``local'' version, perhaps under thename @file{/usr/local/include/sys/signal.h}, to override or add to theone supplied by the system.You can do this by using the option @samp{-I.} for compilation, andwriting a file @file{sys/signal.h} that does what the applicationprogram expects. But making this file include the standard@file{sys/signal.h} is not so easy---writing @samp{#include<sys/signal.h>} in that file doesn't work, because it includes your ownversion of the file, not the standard system version. Used in that fileitself, this leads to an infinite recursion and a fatal error incompilation.@samp{#include </usr/include/sys/signal.h>} would find the proper file,but that is not clean, since it makes an assumption about where thesystem header file is found. This is bad for maintenance, since itmeans that any change in where the system's header files are keptrequires a change somewhere else.@findex #include_nextThe clean way to solve this problem is to use @samp{#include_next}, which means, ``Include the @emph{next} file withthis name.'' This command works like @samp{#include} except insearching for the specified file: it starts searching the list of headerfile directories @emph{after} the directory in which the current filewas found.Suppose you specify @samp{-I /usr/local/include}, and the list ofdirectories to search also includes @file{/usr/include}; and suppose thatboth directories contain a file named @file{sys/signal.h}. Ordinary@samp{#include <sys/signal.h>} finds the file under@file{/usr/local/include}. If that file contains @samp{#include_next<sys/signal.h>}, it starts searching after that directory, and finds thefile in @file{/usr/include}.@node Macros, Conditionals, Header Files, Top@section MacrosA macro is a sort of abbreviation which you can define once and thenuse later. There are many complicated features associated with macrosin the C preprocessor.@menu* Simple Macros:: Macros that always expand the same way.* Argument Macros:: Macros that accept arguments that are substituted into the macro expansion.* Predefined:: Predefined macros that are always available.* Stringification:: Macro arguments converted into string constants.* Concatenation:: Building tokens from parts taken from macro arguments.* Undefining:: Cancelling a macro's definition.* Redefining:: Changing a macro's definition.* Macro Pitfalls:: Macros can confuse the unwary. Here we explain several common problems and strange features.@end menu@node Simple Macros, Argument Macros, Macros, Macros@subsection Simple MacrosA @dfn{simple macro} is a kind of abbreviation. It is a name whichstands for a fragment of code. Some people refer to these as@dfn{manifest constants}.Before you can use a macro, you must @dfn{define} it explicitly with the@samp{#define} command. @samp{#define} is followed by the name of themacro and then the code it should be an abbreviation for. For example,@example#define BUFFER_SIZE 1020@end example@noindentdefines a macro named @samp{BUFFER_SIZE} as an abbreviation for the text@samp{1020}. Therefore, if somewhere after this @samp{#define} commandthere comes a C statement of the form@examplefoo = (char *) xmalloc (BUFFER_SIZE);@end example@noindentthen the C preprocessor will recognize and @dfn{expand} the macro@samp{BUFFER_SIZE}, resulting in@examplefoo = (char *) xmalloc (1020);@end example@noindentthe definition must be a single line; however, it may not end in themiddle of a multi-line string constant or character constant.The use of all upper case for macro names is a standard convention.Programs are easier to read when it is possible to tell at a glance whichnames are macros.Normally, a macro definition must be a single line, like all C preprocessorcommands. (You can split a long macro definition cosmetically withBackslash-Newline.) There is one exception: Newlines can be included inthe macro definition if within a string or character constant. By the sametoken, it is not possible for a macro definition to contain an unbalancedquote character; the definition automatically extends to include thematching quote character that ends the string or character constant.Comments within a macro definition may contain Newlines, which make nodifference since the comments are entirely replaced with Spaces regardlessof their contents.Aside from the above, there is no restriction on what can go in a macrobody. Parentheses need not balance. The body need not resemble valid Ccode. (Of course, you might get error messages from the C compiler whenyou use the macro.)The C preprocessor scans your program sequentially, so macro definitionstake effect at the place you write them. Therefore, the following input tothe C preprocessor@examplefoo = X;#define X 4bar = X;@end example@noindentproduces as output@examplefoo = X;bar = 4;@end exampleAfter the preprocessor expands a macro name, the macro's definition body isappended to the front of the remaining input, and the check for macro callscontinues. Therefore, the macro body can contain calls to other macros.For example, after@example#define BUFSIZE 1020#define TABLESIZE BUFSIZE@end example@noindentthe name @samp{TABLESIZE} when used in the program would go through twostages of expansion, resulting ultimately in @samp{1020}.This is not at all the same as defining @samp{TABLESIZE} to be @samp{1020}.The @samp{#define} for @samp{TABLESIZE} uses exactly the body youspecify---in this case, @samp{BUFSIZE}---and does not check to see whetherit too is the name of a macro. It's only when you @emph{use} @samp{TABLESIZE}that the result of its expansion is checked for more macro names.@xref{Cascaded Macros}.@node Argument Macros, Predefined, Simple Macros, Macros@subsection Macros with ArgumentsA simple macro always stands for exactly the same text, each time it isused. Macros can be more flexible when they accept @dfn{arguments}.Arguments are fragments of code that you supply each time the macro isused. These fragments are included in the expansion of the macro accordingto the directions in the macro definition.To define a macro that uses arguments, you write a @samp{#define} commandwith a list of @dfn{argument names} in parentheses after the name of themacro. The argument names may be any valid C identifiers, separated bycommas and optionally whitespace. The open-parenthesis must follow themacro name immediately, with no space in between.For example, here is a macro that computes the minimum of two numericvalues, as it is defined in many C programs:@example#define min(X, Y) ((X) < (Y) ? (X) : (Y))@end example@noindent(This is not the best way to define a ``minimum'' macro in GNU C.@xref{Side Effects}, for more information.)To use a macro that expects arguments, you write the name of the macrofollowed by a list of @dfn{actual arguments} in parentheses. separated bycommas. The number of actual arguments you give must match the number ofarguments the macro expects. Examples of use of the macro @samp{min}include @samp{min (1, 2)} and @samp{min (x + 28, *p)}.The expansion text of the macro depends on the arguments you use.Each of the argument names of the macro is replaced, throughout themacro definition, with the corresponding actual argument. Using thesame macro @samp{min} defined above, @samp{min (1, 2)} expands into@example((1) < (2) ? (1) : (2))@end example@noindentwhere @samp{1} has been substituted for @samp{X} and @samp{2} for @samp{Y}.Likewise, @samp{min (x + 28, *p)} expands into@example((x + 28) < (*p) ? (x + 28) : (*p))@end exampleParentheses in the actual arguments must balance; a comma withinparentheses does not end an argument. However, there is no requirementfor brackets or braces to balance, and they do not prevent a comma fromseparating arguments. Thus,@examplemacro (array[x = y, x + 1])@end example@noindentpasses two arguments to @code{macro}: @samp{array[x = y} and @samp{x +1]}. If you want to supply @samp{array[x = y, x + 1]} as an argument,you must write it as @samp{array[(x = y, x + 1)]}, which is equivalent Ccode.After the actual arguments are substituted into the macro body, the entireresult is appended to the front of the remaining input, and the check formacro calls continues. Therefore, the actual arguments can contain callsto other macros, either with or without arguments, or even to the samemacro. The macro body can also contain calls to other macros. Forexample, @samp{min (min (a, b), c)} expands into this text:
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -