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

📄 standards.texi

📁 autoconf 2.59版,可用于redhat系统.用于编译原码,编写makefile文件.
💻 TEXI
📖 第 1 页 / 共 5 页
字号:
@end example@node Conditional Compilation@section Conditional CompilationWhen supporting configuration options already known when building yourprogram we prefer using @code{if (... )} over conditional compilation,as in the former case the compiler is able to perform more extensivechecking of all possible code paths.For example, please write@smallexample  if (HAS_FOO)    ...  else    ...@end smallexample@noindentinstead of:@smallexample  #ifdef HAS_FOO    ...  #else    ...  #endif@end smallexampleA modern compiler such as GCC will generate exactly the same code inboth cases, and we have been using similar techniques with good successin several projects.  Of course, the former method assumes that@code{HAS_FOO} is defined as either 0 or 1.While this is not a silver bullet solving all portability problems,and is not always appropriate, following this policy would have savedGCC developers many hours, or even days, per year.In the case of function-like macros like @code{REVERSIBLE_CC_MODE} inGCC which cannot be simply used in @code{if( ...)} statements, there isan easy workaround.  Simply introduce another macro@code{HAS_REVERSIBLE_CC_MODE} as in the following example:@smallexample  #ifdef REVERSIBLE_CC_MODE  #define HAS_REVERSIBLE_CC_MODE 1  #else  #define HAS_REVERSIBLE_CC_MODE 0  #endif@end smallexample@node Program Behavior@chapter Program Behavior for All ProgramsThis @value{CHAPTER} describes conventions for writing robustsoftware.  It also describes general standards for error messages, thecommand line interface, and how libraries should behave.@menu* Semantics::                   Writing robust programs* Libraries::                   Library behavior* Errors::                      Formatting error messages* User Interfaces::             Standards about interfaces generally* Graphical Interfaces::        Standards for graphical interfaces* Command-Line Interfaces::     Standards for command line interfaces* Option Table::                Table of long options* Memory Usage::                When and how to care about memory needs* File Usage::                  Which files to use, and where@end menu@node Semantics@section Writing Robust Programs@cindex arbitrary limits on dataAvoid arbitrary limits on the length or number of @emph{any} datastructure, including file names, lines, files, and symbols, by allocatingall data structures dynamically.  In most Unix utilities, ``long linesare silently truncated''.  This is not acceptable in a GNU utility.@cindex @code{NUL} charactersUtilities reading files should not drop NUL characters, or any othernonprinting characters @emph{including those with codes above 0177}.The only sensible exceptions would be utilities specifically intendedfor interface to certain types of terminals or printersthat can't handle those characters.Whenever possible, try to make programs work properly withsequences of bytes that represent multibyte characters, using encodingssuch as UTF-8 and others.@cindex error messagesCheck every system call for an error return, unless you know you wish toignore errors.  Include the system error text (from @code{perror} orequivalent) in @emph{every} error message resulting from a failingsystem call, as well as the name of the file if any and the name of theutility.  Just ``cannot open foo.c'' or ``stat failed'' is notsufficient.@cindex @code{malloc} return value@cindex memory allocation failureCheck every call to @code{malloc} or @code{realloc} to see if itreturned zero.  Check @code{realloc} even if you are making the blocksmaller; in a system that rounds block sizes to a power of 2,@code{realloc} may get a different block if you ask for less space.In Unix, @code{realloc} can destroy the storage block if it returnszero.  GNU @code{realloc} does not have this bug: if it fails, theoriginal block is unchanged.  Feel free to assume the bug is fixed.  Ifyou wish to run your program on Unix, and wish to avoid lossage in thiscase, you can use the GNU @code{malloc}.You must expect @code{free} to alter the contents of the block that wasfreed.  Anything you want to fetch from the block, you must fetch beforecalling @code{free}.If @code{malloc} fails in a noninteractive program, make that a fatalerror.  In an interactive program (one that reads commands from theuser), it is better to abort the command and return to the commandreader loop.  This allows the user to kill other processes to free upvirtual memory, and then try the command again.@cindex command-line arguments, decodingUse @code{getopt_long} to decode arguments, unless the argument syntaxmakes this unreasonable.When static storage is to be written in during program execution, useexplicit C code to initialize it.  Reserve C initialized declarationsfor data that will not be changed.@c ADR: why?Try to avoid low-level interfaces to obscure Unix data structures (suchas file directories, utmp, or the layout of kernel memory), since theseare less likely to work compatibly.  If you need to find all the filesin a directory, use @code{readdir} or some other high-level interface.These are supported compatibly by GNU.@cindex signal handlingThe preferred signal handling facilities are the BSD variant of@code{signal}, and the @sc{posix} @code{sigaction} function; thealternative USG @code{signal} interface is an inferior design.Nowadays, using the @sc{posix} signal functions may be the easiest wayto make a program portable.  If you use @code{signal}, then on GNU/Linuxsystems running GNU libc version 1, you should include@file{bsd/signal.h} instead of @file{signal.h}, so as to get BSDbehavior.  It is up to you whether to support systems where@code{signal} has only the USG behavior, or give up on them.@cindex impossible conditionsIn error checks that detect ``impossible'' conditions, just abort.There is usually no point in printing any message.  These checksindicate the existence of bugs.  Whoever wants to fix the bugs will haveto read the source code and run a debugger.  So explain the problem withcomments in the source.  The relevant data will be in variables, whichare easy to examine with the debugger, so there is no point moving themelsewhere.Do not use a count of errors as the exit status for a program.@emph{That does not work}, because exit status values are limited to 8bits (0 through 255).  A single run of the program might have 256errors; if you try to return 256 as the exit status, the parent processwill see 0 as the status, and it will appear that the program succeeded.@cindex temporary files@cindex @code{TMPDIR} environment variableIf you make temporary files, check the @code{TMPDIR} environmentvariable; if that variable is defined, use the specified directoryinstead of @file{/tmp}.In addition, be aware that there is a possible security problem whencreating temporary files in world-writable directories.  In C, you canavoid this problem by creating temporary files in this manner:@examplefd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0600);@end example@noindentor by using the @code{mkstemps} function from libiberty.In bash, use @code{set -C} to avoid this problem.@node Libraries@section Library Behavior@cindex librariesTry to make library functions reentrant.  If they need to do dynamicstorage allocation, at least try to avoid any nonreentrancy aside fromthat of @code{malloc} itself.Here are certain name conventions for libraries, to avoid nameconflicts.Choose a name prefix for the library, more than two characters long.All external function and variable names should start with thisprefix.  In addition, there should only be one of these in any givenlibrary member.  This usually means putting each one in a separatesource file.An exception can be made when two external symbols are always usedtogether, so that no reasonable program could use one without theother; then they can both go in the same file.External symbols that are not documented entry points for the usershould have names beginning with @samp{_}.  The @samp{_} should befollowed by the chosen name prefix for the library, to preventcollisions with other libraries.  These can go in the same files withuser entry points if you like.Static functions and variables can be used as you like and need notfit any naming convention.@node Errors@section Formatting Error Messages@cindex formatting error messages@cindex error messages, formattingError messages from compilers should look like this:@example@var{source-file-name}:@var{lineno}: @var{message}@end example@noindentIf you want to mention the column number, use one of these formats:@example@var{source-file-name}:@var{lineno}:@var{column}: @var{message}@var{source-file-name}:@var{lineno}.@var{column}: @var{message}   @end example@noindentLine numbers should start from 1 at the beginning of the file, andcolumn numbers should start from 1 at the beginning of the line.  (Bothof these conventions are chosen for compatibility.)  Calculate columnnumbers assuming that space and all ASCII printing characters haveequal width, and assuming tab stops every 8 columns.The error message can also give both the starting and ending positionsof the erroneous text.  There are several formats so that you canavoid redundant information such as a duplicate line number.Here are the possible formats:@example@var{source-file-name}:@var{lineno-1}.@var{column-1}-@var{lineno-2}.@var{column-2}: @var{message}@var{source-file-name}:@var{lineno-1}.@var{column-1}-@var{column-2}: @var{message}@var{source-file-name}:@var{lineno-1}-@var{lineno-2}: @var{message}@end example@noindentWhen an error is spread over several files, you can use this format:@example@var{file-1}:@var{lineno-1}.@var{column-1}-@var{file-2}:@var{lineno-2}.@var{column-2}: @var{message}@end exampleError messages from other noninteractive programs should look like this:@example@var{program}:@var{source-file-name}:@var{lineno}: @var{message}@end example@noindentwhen there is an appropriate source file, or like this:@example@var{program}: @var{message}@end example@noindentwhen there is no relevant source file.If you want to mention the column number, use this format:@example@var{program}:@var{source-file-name}:@var{lineno}:@var{column}: @var{message}@end exampleIn an interactive program (one that is reading commands from aterminal), it is better not to include the program name in an errormessage.  The place to indicate which program is running is in theprompt or with the screen layout.  (When the same program runs withinput from a source other than a terminal, it is not interactive andwould do best to print error messages using the noninteractive style.)The string @var{message} should not begin with a capital letter whenit follows a program name and/or file name, because that isn't thebeginning of a sentence.  (The sentence conceptually starts at thebeginning of the line.)  Also, it should not end with a period.Error messages from interactive programs, and other messages such asusage messages, should start with a capital letter.  But they should notend with a period.@node User Interfaces@section Standards for Interfaces Generally@cindex program name and its behavior@cindex behavior, dependent on program's namePlease don't make the behavior of a utility depend on the name usedto invoke it.  It is useful sometimes to make a link to a utilitywith a different name, and that should not change what it does.Instead, use a run time option or a compilation switch or bothto select among the alternate behaviors.@cindex output device and program's behaviorLikewise, please don't make the behavior of the program depend on thetype of output device it is used with.  Device independence is animportant principle of the system's design; do not compromise it merelyto save someone from typing an option now and then.  (Variation in errormessage syntax when using a terminal is ok, because that is a side issuethat people do not depend on.)If you think one behavior is most useful when the output is to aterminal, and another is most useful when the output is a file or apipe, then it is usually best to make the default behavior the one thatis useful with output to a terminal, and have an option for the otherbehavior.Compatibility requires certain programs to depend on the type of outputdevice.  It would be disastrous if @code{ls} or @code{sh} did not do soin the way all users expect.  In some of these cases, we supplement theprogram with a preferred alternate version that does not depend on theoutput device type.  For example, we provide a @code{dir} program muchlike @code{ls} except that its default output format is alwaysmulti-column format.@node Graphical Interfaces@section Standards for Graphical Interfaces@cindex graphical user interface@cindex gtkWhen you write a program that provides a graphical user interface,please make it work with X Windows and the GTK toolkit unless thefunctionality specifically requires some alternative (for example,``displaying jpeg images while in console mode'').In addition, please provide a command-line interface to control thefunctionality.  (In many cases, the graphical user interface can be aseparate program which invokes the command-line program.)  This isso that the same jobs can be done from scripts.@cindex corba@cindex gnomePlease also consider providing a CORBA interface (for use from GNOME), alibrary interface (for use from C), and perhaps a keyboard-drivenconsole interface (for use by users from console mode).  Once you aredoing the work to provide the functionality and the graphical interface,these won't be much extra work.@node Command-Line Interfaces@section Standards for Command Line Interfaces@cindex command-line interface@findex getoptIt is a good idea to follow the @sc{posix} guidelines for thecommand-line options of a program.  The easiest way to do this is to use@code{getopt} to parse them.  Note that the GNU version of @code{getopt}will normally permit options anywhere among the arguments unless thespecial argument @samp{--} is used.  This is not what @sc{posix}specifies; it is a GNU extension.@cindex long-named optionsPlease define long-named options that are equivalent to thesingle-letter Unix-style options.  We hope to make GNU more userfriendly this way.  This is easy to do with the GNU function@code{getopt_long}.One of the advantages of long-named options is that they can beconsistent from program to program.  For example, users should be ableto expect the ``verbose'' option of any GNU program which has one, to bespelled precisely @samp{--verbose}.  To achieve this uniformity, look atthe table of common long-option names when you choose the option namesfor your program (@pxref{Option Table}).It is usually a good idea for file names given as ordinary arguments tobe input files only; any output files would be specified using options(preferably @samp{-o} or @samp{--output}).  Even if you allow an outputfile name as an ordinary argument for compatibility, try to provide anoption as another way to specify it.  This will lead to more consistencyamong GNU utilities, and fewer idiosyncracies for users to remember.@cindex standard command-line options@cindex options, standard command-line@cindex CGI programs, standard options for@cindex PATH_INFO, specifying standard options asAll programs should support two standard options: @samp{--version}and @samp{--help}.  CGI programs should accept these as command-lineoptions, and also if given as the @env{PATH_INFO}; for instance,visiting @url{http://example.org/p.cgi/--help} in a browser shouldoutput the same information as inokving @samp{p.cgi --help} from thecommand line.@table @code@cindex @samp{--version} option@item --versionThis option should direct the program to print information about its name,version, origin and legal status, all on standard output, and then exitsuccessfully.  Other options and arguments should be ignored once thisis seen, and the program should not perform its normal function.@cindex canonical name of a program@cindex program's canonical nameThe first line is meant to be easy for a program to parse; the versionnumber proper starts after the last space.  In addition, it containsthe canonical name for this program, in this format:@exampleGNU Emacs 19.30@end example@noindentThe program's name should be a constant string; @emph{don't} compute itfrom @code{argv[0]}.  The idea is to state the standard or canonicalname for the program, not its file name.  There are other ways to findout the precise file name where a command is found in @code{PATH}.If the program is a subsidiary part of a larger package, mention thepackage name in parentheses, like this:@exampleemacsserver (GNU Emacs) 19.30@end example@noindentIf the package has a version number which is different from thisprogram's version number, you can mention the package version numberjust before the close-parenthesis.If you @strong{need} to mention the version numbers of libraries whichare distributed separately from the package which contains this program,you can do so by printing an additional line of version info for eachlibrary you want to mention.  Use the same format for these lines as forthe first line.Please do not mention all of the libraries that the program uses ``justfor completeness''---that would produce a lot of unhelpful clutter.Please mention library version numbers only if you find in practice thatthey are very important to you in debugging.The following line, after the version number line or lines, should be acopyright notice.  If more than one copyright notice is called for, puteach on a separate line.Next should follow a brief statement that the program is free software,and that users are free to copy and change it on certain conditions.  Ifthe program is covered by the GNU GPL, say so here.  Also mention thatthere is no warranty, to the extent permitted by law.It is ok to finish the output with a list of the major authors of theprogram, as a way of giving credit.Here's an example of output that follows these rules:@smallexampleGNU Emacs 19.34.5Copyright (C) 1996 Free Software Foundation, Inc.GNU Emacs comes with NO WARRANTY,to the extent permitted by law.You may redistribute copies of GNU Emacsunder the terms of the GNU General Public License.For more information about these matters,see the files named COPYING.

⌨️ 快捷键说明

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