⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cpp.texi

📁 理解和实践操作系统的一本好书
💻 TEXI
📖 第 1 页 / 共 5 页
字号:
@cindex header fileA header file is a file containing C declarations and macro definitions(@pxref{Macros}) to be shared between several source files.  You requestthe use of a header file in your program by @dfn{including} it, with theC preprocessing directive @samp{#include}.Header files serve two purposes.@itemize @bullet@item@cindex system header filesSystem header files declare the interfaces to parts of the operatingsystem.  You include them in your program to supply the definitions anddeclarations you need to invoke system calls and libraries.@itemYour own header files contain declarations for interfaces between thesource files of your program.  Each time you have a group of relateddeclarations and macro definitions all or most of which are needed inseveral different source files, it is a good idea to create a headerfile for them.@end itemizeIncluding a header file produces the same results as copying the headerfile into each source file that needs it.  Such copying would betime-consuming and error-prone.  With a header file, the relateddeclarations appear in only one place.  If they need to be changed, theycan be changed in one place, and programs that include the header filewill automatically use the new version when next recompiled.  The headerfile eliminates the labor of finding and changing all the copies as wellas the risk that a failure to find one copy will result ininconsistencies within a program.In C, the usual convention is to give header files names that end with@file{.h}.  It is most portable to use only letters, digits, dashes, andunderscores in header file names, and at most one dot.@menu* Include Syntax::* Include Operation::* Search Path::* Once-Only Headers::* Computed Includes::* Wrapper Headers::* System Headers::@end menu@node Include Syntax@section Include Syntax@findex #includeBoth user and system header files are included using the preprocessingdirective @samp{#include}.  It has two variants:@table @code@item #include <@var{file}>This variant is used for system header files.  It searches for a filenamed @var{file} in a standard list of system directories.  You can prependdirectories to this list with the @option{-I} option (@pxref{Invocation}).@item #include "@var{file}"This variant is used for header files of your own program.  Itsearches for a file named @var{file} first in the directory containingthe current file, then in the quote directories and then the samedirectories used for @code{<@var{file}>}.  You can prepend directoriesto the list of quote directories with the @option{-iquote} option.@end tableThe argument of @samp{#include}, whether delimited with quote marks orangle brackets, behaves like a string constant in that comments are notrecognized, and macro names are not expanded.  Thus, @code{@w{#include<x/*y>}} specifies inclusion of a system header file named @file{x/*y}.However, if backslashes occur within @var{file}, they are consideredordinary text characters, not escape characters.  None of the characterescape sequences appropriate to string constants in C are processed.Thus, @code{@w{#include "x\n\\y"}} specifies a filename containing threebackslashes.  (Some systems interpret @samp{\} as a pathname separator.All of these also interpret @samp{/} the same way.  It is most portableto use only @samp{/}.)It is an error if there is anything (other than comments) on the lineafter the file name.@node Include Operation@section Include OperationThe @samp{#include} directive works by directing the C preprocessor toscan the specified file as input before continuing with the rest of thecurrent file.  The output from the preprocessor contains the outputalready generated, followed by the output resulting from the includedfile, followed by the output that comes from the text after the@samp{#include} directive.  For example, if you have a header file@file{header.h} as follows,@smallexamplechar *test (void);@end smallexample@noindentand a main program called @file{program.c} that uses the header file,like this,@smallexampleint x;#include "header.h"intmain (void)@{  puts (test ());@}@end smallexample@noindentthe compiler will see the same token stream as it would if@file{program.c} read@smallexampleint x;char *test (void);intmain (void)@{  puts (test ());@}@end smallexampleIncluded files are not limited to declarations and macro definitions;those are merely the typical uses.  Any fragment of a C program can beincluded from another file.  The include file could even contain thebeginning of a statement that is concluded in the containing file, orthe end of a statement that was started in the including file.  However,an included file must consist of complete tokens.  Comments and stringliterals which have not been closed by the end of an included file areinvalid.  For error recovery, they are considered to end at the end ofthe file.To avoid confusion, it is best if header files contain only completesyntactic units---function declarations or definitions, typedeclarations, etc.The line following the @samp{#include} directive is always treated as aseparate line by the C preprocessor, even if the included file lacks afinal newline.@node Search Path@section Search PathGCC looks in several different places for headers.  On a normal Unixsystem, if you do not instruct it otherwise, it will look for headersrequested with @code{@w{#include <@var{file}>}} in:@smallexample/usr/local/include@var{libdir}/gcc/@var{target}/@var{version}/include/usr/@var{target}/include/usr/include@end smallexampleFor C++ programs, it will also look in @file{/usr/include/g++-v3},first.  In the above, @var{target} is the canonical name of the systemGCC was configured to compile code for; often but not always the same asthe canonical name of the system it runs on.  @var{version} is theversion of GCC in use.You can add to this list with the @option{-I@var{dir}} command lineoption.  All the directories named by @option{-I} are searched, inleft-to-right order, @emph{before} the default directories.  The onlyexception is when @file{dir} is already searched by default.  Inthis case, the option is ignored and the search order for systemdirectories remains unchanged.Duplicate directories are removed from the quote and bracket searchchains before the two chains are merged to make the final search chain.Thus, it is possible for a directory to occur twice in the final searchchain if it was specified in both the quote and bracket chains.You can prevent GCC from searching any of the default directories withthe @option{-nostdinc} option.  This is useful when you are compiling anoperating system kernel or some other program that does not use thestandard C library facilities, or the standard C library itself.@option{-I} options are not ignored as described above when@option{-nostdinc} is in effect.GCC looks for headers requested with @code{@w{#include "@var{file}"}}first in the directory containing the current file, then in thedirectories as specified by @option{-iquote} options, then in the sameplaces it would have looked for a header requested with anglebrackets.  For example, if @file{/usr/include/sys/stat.h} contains@code{@w{#include "types.h"}}, GCC looks for @file{types.h} first in@file{/usr/include/sys}, then in its usual search path.@samp{#line} (@pxref{Line Control}) does not change GCC's idea of thedirectory containing the current file.You may put @option{-I-} at any point in your list of @option{-I} options.This has two effects.  First, directories appearing before the@option{-I-} in the list are searched only for headers requested withquote marks.  Directories after @option{-I-} are searched for allheaders.  Second, the directory containing the current file is notsearched for anything, unless it happens to be one of the directoriesnamed by an @option{-I} switch.  @option{-I-} is deprecated, @option{-iquote}should be used instead.@option{-I. -I-} is not the same as no @option{-I} options at all, and doesnot cause the same behavior for @samp{<>} includes that @samp{""}includes get with no special options.  @option{-I.} searches thecompiler's current working directory for header files.  That may or maynot be the same as the directory containing the current file.If you need to look for headers in a directory named @file{-}, write@option{-I./-}.There are several more ways to adjust the header search path.  They aregenerally less useful.  @xref{Invocation}.@node Once-Only Headers@section Once-Only Headers@cindex repeated inclusion@cindex including just once@cindex wrapper @code{#ifndef}If a header file happens to be included twice, the compiler will processits contents twice.  This is very likely to cause an error, e.g.@: when thecompiler sees the same structure definition twice.  Even if it does not,it will certainly waste time.The standard way to prevent this is to enclose the entire real contentsof the file in a conditional, like this:@smallexample@group/* File foo.  */#ifndef FILE_FOO_SEEN#define FILE_FOO_SEEN@var{the entire file}#endif /* !FILE_FOO_SEEN */@end group@end smallexampleThis construct is commonly known as a @dfn{wrapper #ifndef}.When the header is included again, the conditional will be false,because @code{FILE_FOO_SEEN} is defined.  The preprocessor will skipover the entire contents of the file, and the compiler will not see ittwice.CPP optimizes even further.  It remembers when a header file has awrapper @samp{#ifndef}.  If a subsequent @samp{#include} specifies thatheader, and the macro in the @samp{#ifndef} is still defined, it doesnot bother to rescan the file at all.You can put comments outside the wrapper.  They will not interfere withthis optimization.@cindex controlling macro@cindex guard macroThe macro @code{FILE_FOO_SEEN} is called the @dfn{controlling macro} or@dfn{guard macro}.  In a user header file, the macro name should notbegin with @samp{_}.  In a system header file, it should begin with@samp{__} to avoid conflicts with user programs.  In any kind of headerfile, the macro name should contain the name of the file and someadditional text, to avoid conflicts with other header files.@node Computed Includes@section Computed Includes@cindex computed includes@cindex macros in includeSometimes it is necessary to select one of several different headerfiles to be included into your program.  They might specifyconfiguration parameters to be used on different sorts of operatingsystems, for instance.  You could do this with a series of conditionals,@smallexample#if SYSTEM_1# include "system_1.h"#elif SYSTEM_2# include "system_2.h"#elif SYSTEM_3@dots{}#endif@end smallexampleThat rapidly becomes tedious.  Instead, the preprocessor offers theability to use a macro for the header name.  This is called a@dfn{computed include}.  Instead of writing a header name as the directargument of @samp{#include}, you simply put a macro name there instead:@smallexample#define SYSTEM_H "system_1.h"@dots{}#include SYSTEM_H@end smallexample@noindent@code{SYSTEM_H} will be expanded, and the preprocessor will look for@file{system_1.h} as if the @samp{#include} had been written that wayoriginally.  @code{SYSTEM_H} could be defined by your Makefile with a@option{-D} option.You must be careful when you define the macro.  @samp{#define} savestokens, not text.  The preprocessor has no way of knowing that the macrowill be used as the argument of @samp{#include}, so it generatesordinary tokens, not a header name.  This is unlikely to cause problemsif you use double-quote includes, which are close enough to stringconstants.  If you use angle brackets, however, you may have trouble.The syntax of a computed include is actually a bit more general than theabove.  If the first non-whitespace character after @samp{#include} isnot @samp{"} or @samp{<}, then the entire line is macro-expandedlike running text would be.If the line expands to a single string constant, the contents of thatstring constant are the file to be included.  CPP does not re-examine thestring for embedded quotes, but neither does it process backslashescapes in the string.  Therefore@smallexample#define HEADER "a\"b"#include HEADER@end smallexample@noindentlooks for a file named @file{a\"b}.  CPP searches for the file accordingto the rules for double-quoted includes.If the line expands to a token stream beginning with a @samp{<} tokenand including a @samp{>} token, then the tokens between the @samp{<} andthe first @samp{>} are combined to form the filename to be included.Any whitespace between tokens is reduced to a single space; then anyspace after the initial @samp{<} is retained, but a trailing spacebefore the closing @samp{>} is ignored.  CPP searches for the fileaccording to the rules for angle-bracket includes.In either case, if there are any tokens on the line after the file name,an error occurs and the directive is not processed.  It is also an errorif the result of expansion does not match either of the two expectedforms.These rules are implementation-defined behavior according to the Cstandard.  To minimize the risk of different compilers interpreting yourcomputed includes differently, we recommend you use only a singleobject-like macro which expands to a string constant.  This will also

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -