📄 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 November 23, 2002@c %**end of header@dircategory GNU organization@direntry* Standards: (standards). GNU coding standards.@end direntry@c @setchapternewpage odd@setchapternewpage off@c Put everything in one index (arbitrarily chosen to be the concept index).@syncodeindex fn cp@syncodeindex ky cp@syncodeindex pg cp@syncodeindex vr cp@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@copyingThe GNU coding standards, last updated @value{lastupdate}.Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,2001, 2002 Free Software Foundation, Inc.Permission is granted to copy, distribute and/or modify this documentunder the terms of the GNU Free Documentation License, Version 1.1or any later version published by the Free Software Foundation;with no Invariant Sections, with noFront-Cover Texts, and with no Back-Cover Texts.A copy of the license is included in the section entitled ``GNUFree Documentation License''.@end copying@titlepage@title GNU Coding Standards@author Richard Stallman, et al.@author last updated @value{lastupdate}@page@vskip 0pt plus 1filll@insertcopying@end titlepage@contents@ifnottex@node Top, Preface, (dir), (dir)@top Version@insertcopying@end ifnottex@menu* Preface:: About the GNU Coding Standards* Legal Issues:: 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* References:: References to Non-Free Software or Documentation* Copying This Manual:: How to Make Copies of This Manual* Index:: @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.This release of the GNU Coding Standards was last updated@value{lastupdate}.@cindex where to obtain @code{standards.texi}@cindex downloading this manualIf you did not obtain this file directly from the GNU project andrecently, please check for a newer version. You can get the GNUCoding Standards from the GNU World Wide Web server host in severaldifferent formats: @uref{http://www.gnu.org/prep/standards.text},@uref{http://www.gnu.org/prep/standards.info}, and@uref{http://www.gnu.org/prep/standards.dvi}, as well as theTexinfo ``source'' which is divided in two files:@uref{http://www.gnu.org/prep/standards.texi} and@uref{http://www.gnu.org/prep/make-stds.texi}. The GNU CodingStandards are also available in HTML format starting at@uref{http://www.gnu.org/prep/standards_toc.html}.Corrections or suggestions for this document should be sent to@email{bug-standards@@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.These standards cover the minimum of what is important when writing aGNU package. Likely, the needs for additional standards will come up.Sometimes, you might suggest that such standards be added to thisdocument. If you think your standards would be generally useful, pleasedo suggest them.You should also set standards for your package on many questions notaddressed or not firmly specified here. The most important point is tobe self-consistent---try to stick to the conventions you pick, and tryto document them as much as possible. That way, your program will bemore maintainable by others.The GNU Hello program serves as an example of how to follow the GNUcoding standards for a trivial program which prints @samp{Hello,world!}. @uref{http://www.gnu.org/software/hello/hello.html}.@node Legal Issues@chapter Keeping Free Software Free@cindex legal aspectsThis @value{CHAPTER} discusses how you can make sure that GNU softwareavoids legal difficulties, and other related issues.@menu* Reading Non-Free Code:: Referring to Proprietary Programs* Contributions:: Accepting Contributions* Trademarks:: How We Deal with Trademark Issues@end menu@node Reading Non-Free Code@section Referring to Proprietary Programs@cindex proprietary programs@cindex avoiding proprietary codeDon'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 Contributions@cindex legal papers@cindex accepting contributionsIf the program you are working on is copyrighted by the Free SoftwareFoundation, then when someone else sends you a piece of code to add tothe program, we need legal papers to use it---just as we asked you tosign papers initially. @emph{Each} person who makes a nontrivialcontribution 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.We know it is frustrating to ask for legal papers; it's frustrating forus as well. But if you don't wait, you are going out on a limb---forexample, what if the contributor's employer won't sign a disclaimer?You might have to take that code out again!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 someone send you one implementation, butyou write a different implementation of the same idea, you don't need toget papers.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 Trademarks@section Trademarks@cindex trademarksPlease do not include any trademark acknowledgements in GNU softwarepackages or documentation.Trademark acknowledgements are the statements that such-and-such is atrademark of so-and-so. The GNU Project has no objection to the basicidea of trademarks, but these acknowledgements feel like kowtowing, sowe don't use them. There is no legal requirement for them.What is legally required, as regards other people's trademarks, is toavoid using them in ways which a reader might read as naming or labelingour own programs or activities. For example, since ``Objective C'' is(or at least was) a trademark, we made sure to say that we provide a``compiler for the Objective C language'' rather than an ``Objective Ccompiler''. The latter is meant to be short for the former, but it doesnot explicitly state the relationship, so it could be misinterpreted asusing ``Objective C'' as a label for the compiler rather than for thelanguage.@node Design Advice@chapter General Program Design@cindex program designThis @value{CHAPTER} discusses some of the issues you should take intoaccount when designing your program.@c Standard or ANSI C@c@c In 1989 the American National Standards Institute (ANSI) standardized@c C as standard X3.159-1989. In December of that year the@c International Standards Organization ISO adopted the ANSI C standard@c making minor changes. In 1990 ANSI then re-adopted ISO standard@c C. This version of C is known as either ANSI C or Standard C.@c A major revision of the C Standard appeared in 1999.@menu* Source Language:: Which languges to use.* Compatibility:: Compatibility with other implementations* Using Extensions:: Using non-standard features* Standard C:: Using Standard C features* Conditional Compilation:: Compiling Code Only If A Conditional is True@end menu@node Source Language@section Which Languages to Use@cindex programming langugesWhen you want to use a language that gets compiled and runs at highspeed, the best language to use is C. Using another language is likeusing a non-standard feature: it will cause trouble for users. Even ifGCC supports the other language, users may find it inconvenient to haveto install the compiler for that other language in order to build yourprogram. For example, if you write your program in C++, people willhave to install the GNU C++ compiler in order to compile your program.C 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.So in general it is much better to use C, rather than thecomparable alternatives.But there are two exceptions to that conclusion:@itemize @bullet@itemIt is no problem to use another language to write a tool specificallyintended for use with that language. That is because the only peoplewho want to build the tool will be those who have installed the otherlanguage anyway.@itemIf an application is of interest only to a narrow part of the community,then the question of which language it is written in has less effect onother people, so you may as well please yourself.@end itemizeMany programs are designed to be extensible: they include an interpreterfor a language that is higher level than C. Often much of the programis written in that language, too. The Emacs editor pioneered thistechnique.@cindex GUILEThe standard extensibility interpreter for GNU software is GUILE, whichimplements the language Scheme (an especially clean and simple dialectof Lisp). @uref{http://www.gnu.org/software/guile/}. We don't rejectprograms written in other ``scripting languages'' such as Perl andPython, but using GUILE is very important for the overall consistency ofthe GNU system.@node Compatibility@section Compatibility with Other Implementations@cindex compatibility with C and @sc{posix} standards@cindex @sc{posix} compatibilityWith occasional exceptions, utility programs and libraries for GNUshould be upward compatible with those in Berkeley Unix, and upwardcompatible with Standard C if Standard C specifies theirbehavior, and upward compatible with @sc{posix} if @sc{posix} specifiestheir behavior.When these standards conflict, it is useful to offer compatibilitymodes for each of them.@cindex options for compatibilityStandard C and @sc{posix} prohibit many kinds of extensions. Feelfree to 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. So youshould try to redesign its interface to make it upward compatible.@cindex @code{POSIXLY_CORRECT}, environment variableMany GNU programs suppress extensions that conflict with @sc{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 are welcome regardless of whetherthere is any precedent for them.@node Using Extensions@section Using Non-standard Features@cindex non-standard extensionsMany 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. Using GNU extensions insuch programs would make many users unhappy, so we don't do that.Another exception is for programs that are used as part of compilation:anything that must be compiled with other compilers in order tobootstrap the GNU compilation facilities. If these require the GNUcompiler, then no one can compile them without having them installedalready. That would be extremely troublesome in certain cases.@node Standard C@section Standard C and Pre-Standard C@cindex @sc{ansi} C standard1989 Standard C is widespread enough now that it is ok to use itsfeatures in new programs. There is one exception: do not ever use the``trigraph'' feature of Standard C.1999 Standard C is not widespread yet, so please do not require itsfeatures in programs. It is ok to use its features if they are present.However, it is easy to support pre-standard compilers in most programs,so if you know how to do that, feel free. If a program you aremaintaining has such support, you should try to keep it working.@cindex function prototypesTo support pre-standard C, instead of writing function definitions instandard prototype form,@exampleintfoo (int x, int y)@dots{}@end example@noindentwrite the definition in pre-standard 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 prototypes in all the files where the function is called. And onceyou have the declaration, you normally lose nothing by writing thefunction definition in the pre-standard style.This technique does not work for integer types narrower than @code{int}.If you think of an argument as being of a type narrower than @code{int},declare it as @code{int} instead.There are a few special cases where this technique is hard to use. Forexample, if a function argument needs to hold the system type@code{dev_t}, you run into trouble, because @code{dev_t} is shorter than@code{int} on some machines; but you cannot use @code{int} instead,because @code{dev_t} is wider than @code{int} on some machines. Thereis no type you can safely use on all machines in a non-standarddefinition. The only way to support non-standard C and pass such anargument is to check the width of @code{dev_t} using Autoconf and choosethe argument type accordingly. This may not be worth the trouble.In order to support pre-standard compilers that do not recognizeprototypes, you may want to use a preprocessor macro like this:@example/* Declare the prototype for a general external function. */#if defined (__STDC__) || defined (WINDOWSNT)#define P_(proto) proto#else#define P_(proto) ()#endif@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.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -