?? standards.texi
字號:
\input texinfo @c -*-texinfo-*-@c %**start of header@setfilename standards.info@settitle GNU Coding Standards@c This date is automagically updated when you save this file:@set lastupdate March 13, 1998@c %**end of header@ifinfo@formatSTART-INFO-DIR-ENTRY* Standards: (standards). GNU coding standards.END-INFO-DIR-ENTRY@end format@end ifinfo@c @setchapternewpage odd@setchapternewpage off@c This is used by a cross ref in make-stds.texi@set CODESTD 1@iftex@set CHAPTER chapter@end iftex@ifinfo@set CHAPTER node@end ifinfo@ifinfoGNU Coding StandardsCopyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998 Free Software Foundation, Inc.Permission is granted to make and distribute verbatim copies ofthis manual provided the copyright notice and this permission noticeare preserved on all copies.@ignorePermission is granted to process this file through TeX and print theresults, provided the printed document carries copying permissionnotice identical to this one except for the removal of this paragraph(this paragraph not being relevant to the printed manual).@end ignorePermission is granted to copy and distribute modified versions of thismanual under the conditions for verbatim copying, provided that the entireresulting derived work is distributed under the terms of a permissionnotice identical to this one.Permission is granted to copy and distribute translations of this manualinto another language, under the above conditions for modified versions,except that this permission notice may be stated in a translation approvedby the Free Software Foundation.@end ifinfo@titlepage@title GNU Coding Standards@author Richard Stallman@author last updated @value{lastupdate}@page@vskip 0pt plus 1filllCopyright @copyright{} 1992, 1993, 1994, 1995, 1996, 1997, 1998 Free Software Foundation, Inc.Permission is granted to make and distribute verbatim copies ofthis manual provided the copyright notice and this permission noticeare preserved on all copies.Permission is granted to copy and distribute modified versions of thismanual under the conditions for verbatim copying, provided that the entireresulting derived work is distributed under the terms of a permissionnotice identical to this one.Permission is granted to copy and distribute translations of this manualinto another language, under the above conditions for modified versions,except that this permission notice may be stated in a translation approvedby the Free Software Foundation.@end titlepage@ifinfo@node Top, Preface, (dir), (dir)@top VersionLast updated @value{lastupdate}.@end ifinfo@menu* Preface:: About the GNU Coding Standards* Intellectual Property:: Keeping Free Software Free* Design Advice:: General Program Design* Program Behavior:: Program Behavior for All Programs* Writing C:: Making The Best Use of C* Documentation:: Documenting Programs* Managing Releases:: The Release Process@end menu@node Preface@chapter About the GNU Coding StandardsThe GNU Coding Standards were written by Richard Stallman and other GNUProject volunteers. Their purpose is to make the GNU system clean,consistent, and easy to install. This document can also be read as aguide to writing portable, robust and reliable programs. It focuses onprograms written in C, but many of the rules and principles are usefuleven if you write in another programming language. The rules oftenstate reasons for writing in a certain way.Corrections or suggestions for this document should be sent to@email{gnu@@gnu.org}. If you make a suggestion, please include asuggested new wording for it; our time is limited. We prefer a contextdiff to the @file{standards.texi} or @file{make-stds.texi} files, but ifyou don't have those files, please mail your suggestion anyway.This release of the GNU Coding Standards was last updated@value{lastupdate}.@node Intellectual Property@chapter Keeping Free Software FreeThis @value{CHAPTER} discusses how you can make sure that GNU softwareremains unencumbered.@menu* Reading Non-Free Code:: Referring to Proprietary Programs* Contributions:: Accepting Contributions@end menu@node Reading Non-Free Code@section Referring to Proprietary ProgramsDon't in any circumstances refer to Unix source code for or duringyour work on GNU! (Or to any other proprietary programs.)If you have a vague recollection of the internals of a Unix program,this does not absolutely mean you can't write an imitation of it, butdo try to organize the imitation internally along different lines,because this is likely to make the details of the Unix versionirrelevant and dissimilar to your results.For example, Unix utilities were generally optimized to minimizememory use; if you go for speed instead, your program will be verydifferent. You could keep the entire input file in core and scan itthere instead of using stdio. Use a smarter algorithm discovered morerecently than the Unix program. Eliminate use of temporary files. Doit in one pass instead of two (we did this in the assembler).Or, on the contrary, emphasize simplicity instead of speed. For someapplications, the speed of today's computers makes simpler algorithmsadequate.Or go for generality. For example, Unix programs often have statictables or fixed-size strings, which make for arbitrary limits; usedynamic allocation instead. Make sure your program handles NULs andother funny characters in the input files. Add a programming languagefor extensibility and write part of the program in that language.Or turn some parts of the program into independently usable libraries.Or use a simple garbage collector instead of tracking precisely whento free memory, or use a new GNU facility such as obstacks.@node Contributions@section Accepting ContributionsIf someone else sends you a piece of code to add to the program you areworking on, we need legal papers to use it---the same sort of legalpapers we will need to get from you. @emph{Each} significantcontributor to a program must sign some sort of legal papers in orderfor us to have clear title to the program. The main author alone is notenough.So, before adding in any contributions from other people, please tellus, so we can arrange to get the papers. Then wait until we tell youthat we have received the signed papers, before you actually use thecontribution.This applies both before you release the program and afterward. Ifyou receive diffs to fix a bug, and they make significant changes, weneed legal papers for that change.This also applies to comments and documentation files. For copyrightlaw, comments and code are just text. Copyright applies to all kinds oftext, so we need legal papers for all kinds.You don't need papers for changes of a few lines here or there, sincethey are not significant for copyright purposes. Also, you don't needpapers if all you get from the suggestion is some ideas, not actual codewhich you use. For example, if you write a different solution to theproblem, you don't need to get papers.We know this is frustrating; it's frustrating for us as well. But ifyou don't wait, you are going out on a limb---for example, what if thecontributor's employer won't sign a disclaimer? You might have to takethat code out again!The very worst thing is if you forget to tell us about the othercontributor. We could be very embarrassed in court some day as aresult.We have more detailed advice for maintainers of programs; if you havereached the stage of actually maintaining a program for GNU (whetherreleased or not), please ask us for a copy.@node Design Advice@chapter General Program DesignThis @value{CHAPTER} discusses some of the issues you should take intoaccount when designing your program.@menu* Compatibility:: Compatibility with other implementations* Using Extensions:: Using non-standard features* ANSI C:: Using ANSI C features* Source Language:: Using languages other than C@end menu@node Compatibility@section Compatibility with Other ImplementationsWith occasional exceptions, utility programs and libraries for GNUshould be upward compatible with those in Berkeley Unix, and upwardcompatible with @sc{ansi} C if @sc{ansi} C specifies their behavior, andupward compatible with @sc{POSIX} if @sc{POSIX} specifies theirbehavior.When these standards conflict, it is useful to offer compatibilitymodes for each of them.@sc{ansi} C and @sc{POSIX} prohibit many kinds of extensions. Feel freeto make the extensions anyway, and include a @samp{--ansi},@samp{--posix}, or @samp{--compatible} option to turn them off.However, if the extension has a significant chance of breaking any realprograms or scripts, then it is not really upward compatible. Try toredesign its interface.Many GNU programs suppress extensions that conflict with POSIX if theenvironment variable @code{POSIXLY_CORRECT} is defined (even if it isdefined with a null value). Please make your program recognize thisvariable if appropriate.When a feature is used only by users (not by programs or commandfiles), and it is done poorly in Unix, feel free to replace itcompletely with something totally different and better. (For example,@code{vi} is replaced with Emacs.) But it is nice to offer a compatiblefeature as well. (There is a free @code{vi} clone, so we offer it.)Additional useful features not in Berkeley Unix are welcome.@node Using Extensions@section Using Non-standard FeaturesMany GNU facilities that already exist support a number of convenientextensions over the comparable Unix facilities. Whether to use theseextensions in implementing your program is a difficult question.On the one hand, using the extensions can make a cleaner program.On the other hand, people will not be able to build the programunless the other GNU tools are available. This might cause theprogram to work on fewer kinds of machines.With some extensions, it might be easy to provide both alternatives.For example, you can define functions with a ``keyword'' @code{INLINE}and define that as a macro to expand into either @code{inline} ornothing, depending on the compiler.In general, perhaps it is best not to use the extensions if you canstraightforwardly do without them, but to use the extensions if theyare a big improvement.An exception to this rule are the large, established programs (such asEmacs) which run on a great variety of systems. Such programs wouldbe broken by use of GNU extensions.Another exception is for programs that are used as part ofcompilation: anything that must be compiled with other compilers inorder to bootstrap the GNU compilation facilities. If these requirethe GNU compiler, then no one can compile them without having theminstalled already. That would be no good.@node ANSI C@section @sc{ansi} C and pre-@sc{ansi} CDo not ever use the ``trigraph'' feature of @sc{ansi} C.@sc{ansi} C is widespread enough now that it is ok to write new programsthat use @sc{ansi} C features (and therefore will not work innon-@sc{ansi} compilers). And if a program is already written in@sc{ansi} C, there's no need to convert it to support non-@sc{ansi}compilers.However, it is easy to support non-@sc{ansi} compilers in most programs,so you might still consider doing so when you write a program. Insteadof writing function definitions in @sc{ansi} prototype form,@exampleintfoo (int x, int y)@dots{}@end example@noindentwrite the definition in pre-@sc{ansi} style like this,@exampleintfoo (x, y) int x, y;@dots{}@end example@noindentand use a separate declaration to specify the argument prototype:@exampleint foo (int, int);@end exampleYou need such a declaration anyway, in a header file, to get the benefitof @sc{ansi} C prototypes in all the files where the function is called.And once you have it, you lose nothing by writing the functiondefinition in the pre-@sc{ansi} style.If you don't know non-@sc{ansi} C, there's no need to learn it; justwrite in @sc{ansi} C.@node Source Language@section Using Languages Other Than CUsing a language other than C is like using a non-standard feature: itwill cause trouble for users. Even if GCC supports the other language,users may find it inconvenient to have to install the compiler for thatother language in order to build your program. For example, if youwrite your program in C++, people will have to install the C++ compilerin order to compile your program. Thus, it is better if you write in C.But there are three situations when there is no disadvantage in usingsome other language:@itemize @bullet@itemIt is okay to use another language if your program contains aninterpreter for that language.For example, if your program links with GUILE, it is ok to write part ofthe program in Scheme or another language supported by GUILE.@itemIt is okay to use another language in a tool specifically intended foruse with that language.This is okay because the only people who want to build the tool will bethose who have installed the other language anyway.@itemIf an application is of interest to a narrow community, then perhapsit's not important if the application is inconvenient to install.@end itemizeC has one other advantage over C++ and other compiled languages: morepeople know C, so more people will find it easy to read and modify theprogram if it is written in C.@node Program Behavior@chapter Program Behavior for All ProgramsThis @value{CHAPTER} describes how to write robust software. It alsodescribes general standards for error messages, the command line interface,and how libraries should behave.@menu* Semantics:: Writing robust programs* Libraries:: Library behavior* Errors:: Formatting error messages* User Interfaces:: Standards for command line interfaces* Option Table:: Table of long options.* Memory Usage:: When and how to care about memory needs@end menu@node Semantics@section Writing Robust ProgramsAvoid 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.Utilities reading files should not drop NUL characters, or any othernonprinting characters @emph{including those with codes above 0177}. Theonly sensible exceptions would be utilities specifically intended forinterface to certain types of printers that can't handle those characters.Check 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.Check 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.Use @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 will be supported compatibly by GNU.By default, the GNU system will provide the signal handling functions of@sc{BSD} and of @sc{POSIX}. So GNU software should be written to usethese.In 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.If you make temporary files, check the @code{TMPDIR} environmentvariable; if that variable is defined, use the specified directoryinstead of @file{/tmp}.@node Libraries@section Library BehaviorTry 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.
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -