The GNU coding standards, last updated January 1, 2005.
Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License”.
The GNU Coding Standards were written by Richard Stallman and other GNU Project volunteers. Their purpose is to make the GNU system clean, consistent, and easy to install. This document can also be read as a guide to writing portable, robust and reliable programs. It focuses on programs written in C, but many of the rules and principles are useful even if you write in another programming language. The rules often state reasons for writing in a certain way.
This release of the GNU Coding Standards was last updated January 1, 2005.
If you did not obtain this file directly from the GNU project and recently, please check for a newer version. You can get the GNU Coding Standards from the GNU web server in many different formats, including the Texinfo source, PDF, HTML, DVI, plain text, and more, at: http://www.gnu.org/prep/standards/.
Corrections or suggestions for this document should be sent to bug-standards@gnu.org. If you make a suggestion, please include a suggested new wording for it; our time is limited. We prefer a context diff to the standards.texi or make-stds.texi files, but if you don't have those files, please mail your suggestion anyway.
These standards cover the minimum of what is important when writing a GNU package. Likely, the needs for additional standards will come up. Sometimes, you might suggest that such standards be added to this document. If you think your standards would be generally useful, please do suggest them.
You should also set standards for your package on many questions not addressed or not firmly specified here. The most important point is to be self-consistent—try to stick to the conventions you pick, and try to document them as much as possible. That way, your program will be more maintainable by others.
The GNU Hello program serves as an example of how to follow the GNU coding standards for a trivial program which prints Hello, world!. http://www.gnu.org/software/hello/hello.html.
This chapter discusses how you can make sure that GNU software avoids legal difficulties, and other related issues.
Don't in any circumstances refer to Unix source code for or during your 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, but do try to organize the imitation internally along different lines, because this is likely to make the details of the Unix version irrelevant and dissimilar to your results.
For example, Unix utilities were generally optimized to minimize memory use; if you go for speed instead, your program will be very different. You could keep the entire input file in core and scan it there instead of using stdio. Use a smarter algorithm discovered more recently than the Unix program. Eliminate use of temporary files. Do it in one pass instead of two (we did this in the assembler).
Or, on the contrary, emphasize simplicity instead of speed. For some applications, the speed of today's computers makes simpler algorithms adequate.
Or go for generality. For example, Unix programs often have static tables or fixed-size strings, which make for arbitrary limits; use dynamic allocation instead. Make sure your program handles NULs and other funny characters in the input files. Add a programming language for 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 when to free memory, or use a new GNU facility such as obstacks.
If the program you are working on is copyrighted by the Free Software Foundation, then when someone else sends you a piece of code to add to the program, we need legal papers to use it—just as we asked you to sign papers initially. Each person who makes a nontrivial contribution to a program must sign some sort of legal papers in order for us to have clear title to the program; the main author alone is not enough.
So, before adding in any contributions from other people, please tell us, so we can arrange to get the papers. Then wait until we tell you that we have received the signed papers, before you actually use the contribution.
This applies both before you release the program and afterward. If you receive diffs to fix a bug, and they make significant changes, we need legal papers for that change.
This also applies to comments and documentation files. For copyright law, comments and code are just text. Copyright applies to all kinds of text, so we need legal papers for all kinds.
We know it is frustrating to ask for legal papers; it's frustrating for us as well. But if you don't wait, you are going out on a limb—for example, 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, since they are not significant for copyright purposes. Also, you don't need papers if all you get from the suggestion is some ideas, not actual code which you use. For example, if someone sent you one implementation, but you write a different implementation of the same idea, you don't need to get papers.
The very worst thing is if you forget to tell us about the other contributor. We could be very embarrassed in court some day as a result.
We have more detailed advice for maintainers of programs; if you have reached the stage of actually maintaining a program for GNU (whether released or not), please ask us for a copy. It is also available online for your perusal: http://www.gnu.org/prep/maintain/.
Please do not include any trademark acknowledgements in GNU software packages or documentation.
Trademark acknowledgements are the statements that such-and-such is a trademark of so-and-so. The GNU Project has no objection to the basic idea of trademarks, but these acknowledgements feel like kowtowing, and there is no legal requirement for them, so we don't use them.
What is legally required, as regards other people's trademarks, is to avoid using them in ways which a reader might reasonably understand as naming or labeling our 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 C compiler”. The latter would have been meant as a shorter way of saying the former, but it does not explicitly state the relationship, so it could be misinterpreted as using “Objective C” as a label for the compiler rather than for the language.
Please don't use “win” as an abbreviation for Microsoft Windows in GNU software or documentation. In hacker terminology, calling something a "win" is a form of praise. If you wish to praise Microsoft Windows when speaking on your own, by all means do so, but not in GNU software. Usually we write the word “windows” in full, but when brevity is very important (as in file names and sometimes symbol names), we abbreviate it to “w”. For instance, the files and functions in Emacs that deal with Windows start with w32.
This chapter discusses some of the issues you should take into account when designing your program.
When you want to use a language that gets compiled and runs at high speed, the best language to use is C. Using another language is like using a non-standard feature: it will cause trouble for users. Even if GCC supports the other language, users may find it inconvenient to have to install the compiler for that other language in order to build your program. For example, if you write your program in C++, people will have to install the GNU C++ compiler in order to compile your program.
C has one other advantage over C++ and other compiled languages: more people know C, so more people will find it easy to read and modify the program if it is written in C.
So in general it is much better to use C, rather than the comparable alternatives.
But there are two exceptions to that conclusion:
Many programs are designed to be extensible: they include an interpreter for a language that is higher level than C. Often much of the program is written in that language, too. The Emacs editor pioneered this technique.
The standard extensibility interpreter for GNU software is GUILE, which implements the language Scheme (an especially clean and simple dialect of Lisp). http://www.gnu.org/software/guile/. We don't reject programs written in other “scripting languages” such as Perl and Python, but using GUILE is very important for the overall consistency of the GNU system.
With occasional exceptions, utility programs and libraries for GNU should be upward compatible with those in Berkeley Unix, and upward compatible with Standard C if Standard C specifies their behavior, and upward compatible with posix if posix specifies their behavior.
When these standards conflict, it is useful to offer compatibility modes for each of them.
Standard C and posix prohibit many kinds of extensions. Feel free to make the extensions anyway, and include a --ansi, --posix, or --compatible option to turn them off. However, if the extension has a significant chance of breaking any real programs or scripts, then it is not really upward compatible. So you should try to redesign its interface to make it upward compatible.
Many GNU programs suppress extensions that conflict with posix if the
environment variable POSIXLY_CORRECT is defined (even if it is
defined with a null value). Please make your program recognize this
variable if appropriate.
When a feature is used only by users (not by programs or command
files), and it is done poorly in Unix, feel free to replace it
completely with something totally different and better. (For example,
vi is replaced with Emacs.) But it is nice to offer a compatible
feature as well. (There is a free vi clone, so we offer it.)
Additional useful features are welcome regardless of whether there is any precedent for them.
Many GNU facilities that already exist support a number of convenient extensions over the comparable Unix facilities. Whether to use these extensions 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 program unless the other GNU tools are available. This might cause the program 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” INLINE
and define that as a macro to expand into either inline or
nothing, depending on the compiler.
In general, perhaps it is best not to use the extensions if you can straightforwardly do without them, but to use the extensions if they are a big improvement.
An exception to this rule are the large, established programs (such as Emacs) which run on a great variety of systems. Using GNU extensions in such 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 to bootstrap the GNU compilation facilities. If these require the GNU compiler, then no one can compile them without having them installed already. That would be extremely troublesome in certain cases.
1989 Standard C is widespread enough now that it is ok to use its features 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 its features 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 are maintaining has such support, you should try to keep it working.
To support pre-standard C, instead of writing function definitions in standard prototype form,
int
foo (int x, int y)
...
write the definition in pre-standard style like this,
int
foo (x, y)
int x, y;
...
and use a separate declaration to specify the argument prototype:
int foo (int, int);
You need such a declaration anyway, in a header file, to get the benefit of prototypes in all the files where the function is called. And once you have the declaration, you normally lose nothing by writing the function definition in the pre-standard style.
This technique does not work for integer types narrower than int.
If you think of an argument as being of a type narrower than int,
declare it as int instead.
There are a few special cases where this technique is hard to use. For
example, if a function argument needs to hold the system type
dev_t, you run into trouble, because dev_t is shorter than
int on some machines; but you cannot use int instead,
because dev_t is wider than int on some machines. There
is no type you can safely use on all machines in a non-standard
definition. The only way to support non-standard C and pass such an
argument is to check the width of dev_t using Autoconf and choose
the argument type accordingly. This may not be worth the trouble.
In order to support pre-standard compilers that do not recognize prototypes, you may want to use a preprocessor macro like this:
/* Declare the prototype for a general external function. */
#if defined (__STDC__) || defined (WINDOWSNT)
#define P_(proto) proto
#else
#define P_(proto) ()
#endif
When supporting configuration options already known when building your
program we prefer using if (... ) over conditional compilation,
as in the former case the compiler is able to perform more extensive
checking of all possible code paths.
For example, please write
if (HAS_FOO)
...
else
...
instead of:
#ifdef HAS_FOO
...
#else
...
#endif
A modern compiler such as GCC will generate exactly the same code in
both cases, and we have been using similar techniques with good success
in several projects. Of course, the former method assumes that
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 saved GCC developers many hours, or even days, per year.
In the case of function-like macros like REVERSIBLE_CC_MODE in
GCC which cannot be simply used in if( ...) statements, there is
an easy workaround. Simply introduce another macro
HAS_REVERSIBLE_CC_MODE as in the following example:
#ifdef REVERSIBLE_CC_MODE
#define HAS_REVERSIBLE_CC_MODE 1
#else
#define HAS_REVERSIBLE_CC_MODE 0
#endif
This chapter describes conventions for writing robust software. It also describes general standards for error messages, the command line interface, and how libraries should behave.
Avoid arbitrary limits on the length or number of any data structure, including file names, lines, files, and symbols, by allocating all data structures dynamically. In most Unix utilities, “long lines are silently truncated”. This is not acceptable in a GNU utility.
Utilities reading files should not drop NUL characters, or any other nonprinting characters including those with codes above 0177. The only sensible exceptions would be utilities specifically intended for interface to certain types of terminals or printers that can't handle those characters. Whenever possible, try to make programs work properly with sequences of bytes that represent multibyte characters, using encodings such as UTF-8 and others.
Check every system call for an error return, unless you know you wish to
ignore errors. Include the system error text (from perror or
equivalent) in every error message resulting from a failing
system call, as well as the name of the file if any and the name of the
utility. Just “cannot open foo.c” or “stat failed” is not
sufficient.
Check every call to malloc or realloc to see if it
returned zero. Check realloc even if you are making the block
smaller; in a system that rounds block sizes to a power of 2,
realloc may get a different block if you ask for less space.
In Unix, realloc can destroy the storage block if it returns
zero. GNU realloc does not have this bug: if it fails, the
original block is unchanged. Feel free to assume the bug is fixed. If
you wish to run your program on Unix, and wish to avoid lossage in this
case, you can use the GNU malloc.
You must expect free to alter the contents of the block that was
freed. Anything you want to fetch from the block, you must fetch before
calling free.
If malloc fails in a noninteractive program, make that a fatal
error. In an interactive program (one that reads commands from the
user), it is better to abort the command and return to the command
reader loop. This allows the user to kill other processes to free up
virtual memory, and then try the command again.
Use getopt_long to decode arguments, unless the argument syntax
makes this unreasonable.
When static storage is to be written in during program execution, use explicit C code to initialize it. Reserve C initialized declarations for data that will not be changed.
Try to avoid low-level interfaces to obscure Unix data structures (such
as file directories, utmp, or the layout of kernel memory), since these
are less likely to work compatibly. If you need to find all the files
in a directory, use readdir or some other high-level interface.
These are supported compatibly by GNU.
The preferred signal handling facilities are the BSD variant of
signal, and the posix sigaction function; the
alternative USG signal interface is an inferior design.
Nowadays, using the posix signal functions may be the easiest way
to make a program portable. If you use signal, then on GNU/Linux
systems running GNU libc version 1, you should include
bsd/signal.h instead of signal.h, so as to get BSD
behavior. It is up to you whether to support systems where
signal has only the USG behavior, or give up on them.
In error checks that detect “impossible” conditions, just abort. There is usually no point in printing any message. These checks indicate the existence of bugs. Whoever wants to fix the bugs will have to read the source code and run a debugger. So explain the problem with comments in the source. The relevant data will be in variables, which are easy to examine with the debugger, so there is no point moving them elsewhere.
Do not use a count of errors as the exit status for a program. That does not work, because exit status values are limited to 8 bits (0 through 255). A single run of the program might have 256 errors; if you try to return 256 as the exit status, the parent process will see 0 as the status, and it will appear that the program succeeded.
If you make temporary files, check the TMPDIR environment
variable; if that variable is defined, use the specified directory
instead of /tmp.
In addition, be aware that there is a possible security problem when creating temporary files in world-writable directories. In C, you can avoid this problem by creating temporary files in this manner:
fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0600);
or by using the mkstemps function from libiberty.
In bash, use set -C to avoid this problem.
Try to make library functions reentrant. If they need to do dynamic
storage allocation, at least try to avoid any nonreentrancy aside from
that of malloc itself.
Here are certain name conventions for libraries, to avoid name conflicts.
Choose a name prefix for the library, more than two characters long. All external function and variable names should start with this prefix. In addition, there should only be one of these in any given library member. This usually means putting each one in a separate source file.
An exception can be made when two external symbols are always used together, so that no reasonable program could use one without the other; then they can both go in the same file.
External symbols that are not documented entry points for the user should have names beginning with _. The _ should be followed by the chosen name prefix for the library, to prevent collisions with other libraries. These can go in the same files with user entry points if you like.
Static functions and variables can be used as you like and need not fit any naming convention.
Error messages from compilers should look like this:
source-file-name:lineno: message
If you want to mention the column number, use one of these formats:
source-file-name:lineno:column: message
source-file-name:lineno.column: message
Line numbers should start from 1 at the beginning of the file, and column numbers should start from 1 at the beginning of the line. (Both of these conventions are chosen for compatibility.) Calculate column numbers assuming that space and all ASCII printing characters have equal width, and assuming tab stops every 8 columns.
The error message can also give both the starting and ending positions of the erroneous text. There are several formats so that you can avoid redundant information such as a duplicate line number. Here are the possible formats:
source-file-name:lineno-1.column-1-lineno-2.column-2: message
source-file-name:lineno-1.column-1-column-2: message
source-file-name:lineno-1-lineno-2: message
When an error is spread over several files, you can use this format:
file-1:lineno-1.column-1-file-2:lineno-2.column-2: message
Error messages from other noninteractive programs should look like this:
program:source-file-name:lineno: message
when there is an appropriate source file, or like this:
program: message
when there is no relevant source file.
If you want to mention the column number, use this format:
program:source-file-name:lineno:column: message
In an interactive program (one that is reading commands from a terminal), it is better not to include the program name in an error message. The place to indicate which program is running is in the prompt or with the screen layout. (When the same program runs with input from a source other than a terminal, it is not interactive and would do best to print error messages using the noninteractive style.)
The string message should not begin with a capital letter when it follows a program name and/or file name, because that isn't the beginning of a sentence. (The sentence conceptually starts at the beginning of the line.) Also, it should not end with a period.
Error messages from interactive programs, and other messages such as usage messages, should start with a capital letter. But they should not end with a period.
Please don't make the behavior of a utility depend on the name used to invoke it. It is useful sometimes to make a link to a utility with a different name, and that should not change what it does.
Instead, use a run time option or a compilation switch or both to select among the alternate behaviors.
Likewise, please don't make the behavior of the program depend on the type of output device it is used with. Device independence is an important principle of the system's design; do not compromise it merely to save someone from typing an option now and then. (Variation in error message syntax when using a terminal is ok, because that is a side issue that people do not depend on.)
If you think one behavior is most useful when the output is to a terminal, and another is most useful when the output is a file or a pipe, then it is usually best to make the default behavior the one that is useful with output to a terminal, and have an option for the other behavior.
Compatibility requires certain programs to depend on the type of output
device. It would be disastrous if ls or sh did not do so
in the way all users expect. In some of these cases, we supplement the
program with a preferred alternate version that does not depend on the
output device type. For example, we provide a dir program much
like ls except that its default output format is always
multi-column format.
When you write a program that provides a graphical user interface, please make it work with X Windows and the GTK+ toolkit unless the functionality specifically requires some alternative (for example, “displaying jpeg images while in console mode”).
In addition, please provide a command-line interface to control the functionality. (In many cases, the graphical user interface can be a separate program which invokes the command-line program.) This is so that the same jobs can be done from scripts.
Please also consider providing a CORBA interface (for use from GNOME), a library interface (for use from C), and perhaps a keyboard-driven console interface (for use by users from console mode). Once you are doing the work to provide the functionality and the graphical interface, these won't be much extra work.
It is a good idea to follow the posix guidelines for the
command-line options of a program. The easiest way to do this is to use
getopt to parse them. Note that the GNU version of getopt
will normally permit options anywhere among the arguments unless the
special argument -- is used. This is not what posix
specifies; it is a GNU extension.
Please define long-named options that are equivalent to the
single-letter Unix-style options. We hope to make GNU more user
friendly this way. This is easy to do with the GNU function
getopt_long.
One of the advantages of long-named options is that they can be consistent from program to program. For example, users should be able to expect the “verbose” option of any GNU program which has one, to be spelled precisely --verbose. To achieve this uniformity, look at the table of common long-option names when you choose the option names for your program (see Option Table).
It is usually a good idea for file names given as ordinary arguments to be input files only; any output files would be specified using options (preferably -o or --output). Even if you allow an output file name as an ordinary argument for compatibility, try to provide an option as another way to specify it. This will lead to more consistency among GNU utilities, and fewer idiosyncracies for users to remember.
All programs should support two standard options: --version and --help. CGI programs should accept these as command-line options, and also if given as the PATH_INFO; for instance, visiting http://example.org/p.cgi/–help in a browser should output the same information as inokving p.cgi --help from the command line.
--versionThe first line is meant to be easy for a program to parse; the version number proper starts after the last space. In addition, it contains the canonical name for this program, in this format:
GNU Emacs 19.30
The program's name should be a constant string; don't compute it
from argv[0]. The idea is to state the standard or canonical
name for the program, not its file name. There are other ways to find
out the precise file name where a command is found in PATH.
If the program is a subsidiary part of a larger package, mention the package name in parentheses, like this:
emacsserver (GNU Emacs) 19.30
If the package has a version number which is different from this program's version number, you can mention the package version number just before the close-parenthesis.
If you need to mention the version numbers of libraries which are distributed separately from the package which contains this program, you can do so by printing an additional line of version info for each library you want to mention. Use the same format for these lines as for the first line.
Please do not mention all of the libraries that the program uses “just for completeness”—that would produce a lot of unhelpful clutter. Please mention library version numbers only if you find in practice that they are very important to you in debugging.
The following line, after the version number line or lines, should be a copyright notice. If more than one copyright notice is called for, put each 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. If the program is covered by the GNU GPL, say so here. Also mention that there is no warranty, to the extent permitted by law.
It is ok to finish the output with a list of the major authors of the program, as a way of giving credit.
Here's an example of output that follows these rules:
GNU Emacs 19.34.5
Copyright (C) 1996 Free Software Foundation, Inc.
GNU Emacs comes with NO WARRANTY,
to the extent permitted by law.
You may redistribute copies of GNU Emacs
under the terms of the GNU General Public License.
For more information about these matters,
see the files named COPYING.
You should adapt this to your program, of course, filling in the proper year, copyright holder, name of program, and the references to distribution terms, and changing the rest of the wording as necessary.
This copyright notice only needs to mention the most recent year in which changes were made—there's no need to list the years for previous versions' changes. You don't have to mention the name of the program in these notices, if that is inconvenient, since it appeared in the first line.
Translations of the above lines must preserve the validity of the copyright notices (see Internationalization). If the translation's character set supports it, the (C) should be replaced with the copyright symbol, as follows:
©
Write the word “Copyright” exactly like that, in English. Do not translate it into another language. International treaties recognize the English word “Copyright”; translations into other languages do not have legal significance.
--helpNear the end of the --help option's output there should be a line that says where to mail bug reports. It should have this format:
Report bugs to mailing-address.
Here is a table of long options used by GNU programs. It is surely incomplete, but we aim to list all the options that a new program might want to be compatible with. If you use names not already in the table, please send bug-standards@gnu.org a list of them, with their meanings, so we can update the table.
tar.
du, ls, nm, stty, uname,
and unexpand.
diff.
ls.
etags, tee, time;
-r in tar.
cp.
shar.
m4.
diff.
gawk.
recode.
wdiff.
ptx.
wdiff.
ctags.
shar.
tac.
cpio and diff.
shar.
cpio and tar.
head and tail.
ptx.
head, split, and tail.
etags.
tar.
chgrp and chown.
ls.
recode.
su;
-x in GDB.
tar.
gawk.
tar and shar.
tar.
tar.
diff.
gawk.
ptx, recode, and wdiff;
-W copyright in gawk.
who.
du.
tar and cpio.
shar.
ctags.
touch.
m4;
-t in Bison.
m4.
ctags.
tar.
chgrp, chown, cpio, du,
ls, and tar.
du.
recode.
look.
tar.
csplit.
ls, it
means to show directories themselves rather than their contents. In
rm and ln, it means to not treat links to directories
specially.
strip.
strip.
diff.
csplit.
wdiff.
wdiff.
diff.
xargs.
makeinfo.
m4.
ls.
tar.
xargs.
unshar.
diff.
sed.
nm.
cpio;
-x in tar.
finger.
su.
m4.
info, gawk, Make, mt, and tar;
-n in sed;
-r in touch.
gawk.
ls.
tar.
makeinfo.
ptx.
tail.
makeinfo.
cp, ln, mv, and rm.
shar.
ls, time, and ptx.
m4.
ptx.
tar.
ul.
recode.
install.
tar and shar.
m4.
objdump and recode
who.
shar.
ls.
makeinfo, output HTML.
who.
diff.
ls;
-x in recode.
diff.
ls.
diff.
look and ptx;
-i in diff and wdiff.
ptx.
etags.
tee.
diff.
diff.
tar.
etags;
-I in m4.
tar.
expand.
diff.
ls.
cp, ln, mv, rm;
-e in m4;
-p in xargs;
-w in tar.
shar.
date
csplit.
du and ls.
etags.
wdiff.
shar.
split.
split, head, and tail.
cpio.
gawk.
cpio;
-l in recode.
tar.
ls.
su.
uname.
ptx.
hello and uname.
cpio.
xargs.
xargs.
xargs.
xargs.
who.
who.
diff.
shar.
install, mkdir, and mkfifo.
tar.
tar.
m4.
shar.
shar.
shar.
wdiff.
touch.
etags.
wdiff.
cp.
wdiff.
shar.
gprof.
etags.
nm.
makeinfo.
gprof.
gprof.
shar.
makeinfo.
emacsclient.
info.
uname.
cpio.
objdump.
xargs.
cat.
cat.
nm.
cpio and ls.
tar.
tar, cp, and du.
ptx.
gprof.
gprof.
getopt, fdlist, fdmount,
fdmountd, and fdumount.
shar.
rm.
unshar.
install.
diff.
makeinfo.
mkdir and rmdir.
ul.
cpio.
finger.
cpio and tar.
gawk.
m4.
csplit.
tar and cp.
su.
cpio.
tar.
tar.
diff.
cmp.
nm.
nm.
wdiff.
ed.
shar.
shar
ls.
diff.
gawk.
tar.
tar.
chgrp, chown, cp, ls, diff,
and rm.
makeinfo.
ptx.
tac and etags.
uname.
m4.
objdump.
cpio.
xargs.
diff.
cpio.
ls and nm.
diff.
ptx.
tar.
tar.
stty.
ptx.
du.
tac.
recode to chose files or pipes for sequencing passes.
su.
cat.
diff.
cat.
diff.
cat.
ls.
ls.
gawk.
tar.
diff.
unshar.
shar.
cat.
wdiff.
wdiff.
tar and diff to specify which file within
a directory to start processing with.
wdiff.
shar.
recode.
install.
strip.
strip.
shar.
cp, ln, mv.
csplit.
gprof.
du.
ln.
objdump.
m4.
uname.
expand and unexpand.
ls.
tput and ul.
-t in wdiff.
diff.
shar.
ls and touch.
tar.
du.
ranlib, and recode.
m4.
hello;
-W traditional in gawk;
-G in ed, m4, and ptx.
ctags.
ctags.
ptx.
tar.
cpio.
m4.
nm.
cp, ctags, mv, tar.
gawk; same as --help.
shar.
shar.
tar.
cp, ln, mv.
ctags.
tar.
shar.
ls and ptx.
ptx.
who.
gprof.
If a program typically uses just a few meg of memory, don't bother making any effort to reduce memory usage. For example, if it is impractical for other reasons to operate on files more than a few meg long, it is reasonable to read entire input files into core to operate on them.
However, for programs such as cat or tail, that can
usefully operate on very large files, it is important to avoid using a
technique that would artificially limit the size of files it can handle.
If a program works by lines and could be applied to arbitrary
user-supplied input files, it should keep only a line in memory, because
this is not very hard and users will want to be able to operate on input
files that are bigger than will fit in core all at once.
If your program creates complicated data structures, just make them in
core and give a fatal error if malloc returns zero.
Programs should be prepared to operate when /usr and /etc are read-only file systems. Thus, if the program manages log files, lock files, backup files, score files, or any other files which are modified for internal purposes, these files should not be stored in /usr or /etc.
There are two exceptions. /etc is used to store system configuration information; it is reasonable for a program to modify files in /etc when its job is to update the system configuration. Also, if the user explicitly asks to modify one file in a directory, it is reasonable for the program to store other files in the same directory.
This chapter provides advice on how best to use the C language when writing GNU software.
It is important to put the open-brace that starts the body of a C function in column zero, and avoid putting any other open-brace or open-parenthesis or open-bracket in column zero. Several tools look for open-braces in column zero to find the beginnings of C functions. These tools will not work on code not formatted that way.
It is also important for function definitions to start the name of the function in column zero. This helps people to search for function definitions, and may also help certain tools recognize them. Thus, the proper format is this:
static char *
concat (s1, s2) /* Name starts in column zero here */
char *s1, *s2;
{ /* Open brace in column zero here */
...
}
or, if you want to use Standard C syntax, format the definition like this:
static char *
concat (char *s1, char *s2)
{
...
}
In Standard C, if the arguments don't fit nicely on one line, split it like this:
int
lots_of_args (int an_integer, long a_long, short a_short,
double a_double, float a_float)
...
The rest of this section gives our recommendations for other aspects of
C formatting style, which is also the default style of the indent
program in version 1.2 and newer. It corresponds to the options
-nbad -bap -nbc -bbo -bl -bli2 -bls -ncdb -nce -cp1 -cs -di2
-ndj -nfc1 -nfca -hnl -i2 -ip5 -lp -pcs -psl -nsc -nsob
We don't think of these recommendations as requirements, because it causes no problems for users if two different programs have different formatting styles.
But whatever style you use, please use it consistently, since a mixture of styles within one program tends to look ugly. If you are contributing changes to an existing program, please follow the style of that program.
For the body of the function, our recommended style looks like this:
if (x < foo (y, z))
haha = bar[4] + 5;
else
{
while (z)
{
haha += foo (z, z);
z--;
}
return ++x + bar ();
}
We find it easier to read a program when it has spaces before the open-parentheses and after the commas. Especially after the commas.
When you split an expression into multiple lines, split it before an operator, not after one. Here is the right way:
if (foo_this_is_long && bar > win (x, y, z)
&& remaining_condition)
Try to avoid having two operators of different precedence at the same level of indentation. For example, don't write this:
mode = (inmode[j] == VOIDmode
|| GET_MODE_SIZE (outmode[j]) > GET_MODE_SIZE (inmode[j])
? outmode[j] : inmode[j]);
Instead, use extra parentheses so that the indentation shows the nesting:
mode = ((inmode[j] == VOIDmode
|| (GET_MODE_SIZE (outmode[j]) > GET_MODE_SIZE (inmode[j])))
? outmode[j] : inmode[j]);
Insert extra parentheses so that Emacs will indent the code properly. For example, the following indentation looks nice if you do it by hand,
v = rup->ru_utime.tv_sec*1000 + rup->ru_utime.tv_usec/1000
+ rup->ru_stime.tv_sec*1000 + rup->ru_stime.tv_usec/1000;
but Emacs would alter it. Adding a set of parentheses produces something that looks equally nice, and which Emacs will preserve:
v = (rup->ru_utime.tv_sec*1000 + rup->ru_utime.tv_usec/1000
+ rup->ru_stime.tv_sec*1000 + rup->ru_stime.tv_usec/1000);
Format do-while statements like this:
do
{
a = foo (a);
}
while (a > 0);
Please use formfeed characters (control-L) to divide the program into pages at logical places (but not within a function). It does not matter just how long the pages are, since they do not have to fit on a printed page. The formfeeds should appear alone on lines by themselves.
Every program should start with a comment saying briefly what it is for. Example: fmt - filter for simple filling of text.
Please write the comments in a GNU program in English, because English is the one language that nearly all programmers in all countries can read. If you do not write English well, please write comments in English as well as you can, then ask other people to help rewrite them. If you can't write comments in English, please find someone to work with you and translate your comments into English.
Please put a comment on each function saying what the function does,
what sorts of arguments it gets, and what the possible values of
arguments mean and are used for. It is not necessary to duplicate in
words the meaning of the C argument declarations, if a C type is being
used in its customary fashion. If there is anything nonstandard about
its use (such as an argument of type char * which is really the
address of the second character of a string, not the first), or any
possible values that would not work the way one would expect (such as,
that strings containing newlines are not guaranteed to work), be sure
to say so.
Also explain the significance of the return value, if there is one.
Please put two spaces after the end of a sentence in your comments, so that the Emacs sentence commands will work. Also, please write complete sentences and capitalize the first word. If a lower-case identifier comes at the beginning of a sentence, don't capitalize it! Changing the spelling makes it a different identifier. If you don't like starting a sentence with a lower case letter, write the sentence differently (e.g., “The identifier lower-case is ...”).
The comment on a function is much clearer if you use the argument names to speak about the argument values. The variable name itself should be lower case, but write it in upper case when you are speaking about the value rather than the variable itself. Thus, “the inode number NODE_NUM” rather than “an inode”.
There is usually no purpose in restating the name of the function in the comment before it, because the reader can see that for himself. There might be an exception when the comment is so long that the function itself would be off the bottom of the screen.
There should be a comment on each static variable as well, like this:
/* Nonzero means truncate lines in the display;
zero means continue them. */
int truncate_lines;
Every #endif should have a comment, except in the case of short conditionals (just a few lines) that are not nested. The comment should state the condition of the conditional that is ending, including its sense. #else should have a comment describing the condition and sense of the code that follows. For example:
#ifdef foo
...
#else /* not foo */
...
#endif /* not foo */
#ifdef foo
...
#endif /* foo */
but, by contrast, write the comments this way for a #ifndef:
#ifndef foo
...
#else /* foo */
...
#endif /* foo */
#ifndef foo
...
#endif /* not foo */
Please explicitly declare the types of all objects. For example, you
should explicitly declare all arguments to functions, and you should
declare functions to return int rather than omitting the
int.
Some programmers like to use the GCC -Wall option, and change the code whenever it issues a warning. If you want to do this, then do. Other programmers prefer not to use -Wall, because it gives warnings for valid and legitimate code which they do not want to change. If you want to do this, then do. The compiler should be your servant, not your master.
Declarations of external functions and functions to appear later in the
source file should all go in one place near the beginning of the file
(somewhere before the first function definition in the file), or else
should go in a header file. Don't put extern declarations inside
functions.
It used to be common practice to use the same local variables (with
names like tem) over and over for different values within one
function. Instead of doing this, it is better to declare a separate local
variable for each distinct purpose, and give it a name which is
meaningful. This not only makes programs easier to understand, it also
facilitates optimization by good compilers. You can also move the
declaration of each local variable into the smallest scope that includes
all its uses. This makes the program even cleaner.
Don't use local variables or parameters that shadow global identifiers.
Don't declare multiple variables in one declaration that spans lines. Start a new declaration on each line, instead. For example, instead of this:
int foo,
bar;
write either this:
int foo, bar;
or this:
int foo;
int bar;
(If they are global variables, each should have a comment preceding it anyway.)
When you have an if-else statement nested in another
if statement, always put braces around the if-else.
Thus, never write like this:
if (foo)
if (bar)
win ();
else
lose ();
always like this:
if (foo)
{
if (bar)
win ();
else
lose ();
}
If you have an if statement nested inside of an else
statement, either write else if on one line, like this,
if (foo)
...
else if (bar)
...
with its then-part indented like the preceding then-part,
or write the nested if within braces like this:
if (foo)
...
else
{
if (bar)
...
}
Don't declare both a structure tag and variables or typedefs in the same declaration. Instead, declare the structure tag separately and then use it to declare the variables or typedefs.
Try to avoid assignments inside if-conditions. For example,
don't write this:
if ((foo = (char *) malloc (sizeof *foo)) == 0)
fatal ("virtual memory exhausted");
instead, write this:
foo = (char *) malloc (sizeof *foo);
if (foo == 0)
fatal ("virtual memory exhausted");
Don't make the program ugly to placate lint. Please don't insert any
casts to void. Zero without a cast is perfectly fine as a null
pointer constant, except when calling a varargs function.
The names of global variables and functions in a program serve as comments of a sort. So don't choose terse names—instead, look for names that give useful information about the meaning of the variable or function. In a GNU program, names should be English, like other comments.
Local variable names can be shorter, because they are used only within one context, where (presumably) comments explain their purpose.
Try to limit your use of abbreviations in symbol names. It is ok to make a few abbreviations, explain what they mean, and then use them frequently, but don't use lots of obscure abbreviations.
Please use underscores to separate words in a name, so that the Emacs
word commands can be useful within them. Stick to lower case; reserve
upper case for macros and enum constants, and for name-prefixes
that follow a uniform convention.
For example, you should use names like ignore_space_change_flag;
don't use names like iCantReadThis.
Variables that indicate whether command-line options have been specified should be named after the meaning of the option, not after the option-letter. A comment should state both the exact meaning of the option and its letter. For example,
/* Ignore changes in horizontal whitespace (-b). */
int ignore_space_change_flag;
When you want to define names with constant integer values, use
enum rather than #define. GDB knows about enumeration
constants.
You might want to make sure that none of the file names would conflict
the files were loaded onto an MS-DOS file system which shortens the
names. You can use the program doschk to test for this.
Some GNU programs were designed to limit themselves to file names of 14
characters or less, to avoid file name conflicts if they are read into
older System V systems. Please preserve this feature in the existing
GNU programs that have it, but there is no need to do this in new GNU
programs. doschk also reports file names longer than 14
characters.
In the Unix world, “portability” refers to porting to different Unix versions. For a GNU program, this kind of portability is desirable, but not paramount.
The primary purpose of GNU software is to run on top of the GNU kernel, compiled with the GNU C compiler, on various types of cpu. So the kinds of portability that are absolutely necessary are quite limited. But it is important to support Linux-based GNU systems, since they are the form of GNU that is popular.
Beyond that, it is good to support the other free operating systems (*BSD), and it is nice to support other Unix-like systems if you want to. Supporting a variety of Unix-like systems is desirable, although not paramount. It is usually not too hard, so you may as well do it. But you don't have to consider it an obligation, if it does turn out to be hard.
The easiest way to achieve portability to most Unix-like systems is to use Autoconf. It's unlikely that your program needs to know more information about the host platform than Autoconf can provide, simply because most of the programs that need such knowledge have already been written.
Avoid using the format of semi-internal data bases (e.g., directories)
when there is a higher-level alternative (readdir).
As for systems that are not like Unix, such as MSDOS, Windows, the Macintosh, VMS, and MVS, supporting them is often a lot of work. When that is the case, it is better to spend your time adding features that will be useful on GNU and GNU/Linux, rather than on supporting other incompatible systems.
If you do support Windows, please do not abbreviate it as “win”. In
hacker terminology, calling something a “win” is a form of praise.
You're free to praise Microsoft Windows on your own if you want, but
please don't do this in GNU packages. Instead of abbreviating
“Windows” to “un”, you can write it in full or abbreviate it to
“woe” or “w”. In GNU Emacs, for instance, we use w32 in
file names of Windows-specific files, but the macro for Windows
conditionals is called WINDOWSNT.
It is a good idea to define the “feature test macro”
_GNU_SOURCE when compiling your C files. When you compile on GNU
or GNU/Linux, this will enable the declarations of GNU library extension
functions, and that will usually give you a compiler error message if
you define the same function names in some other way in your program.
(You don't have to actually use these functions, if you prefer
to make the program more portable to other systems.)
But whether or not you use these GNU extensions, you should avoid using their names for any other meanings. Doing so would make it hard to move your code into other GNU programs.
Even GNU systems will differ because of differences among cpu
types—for example, difference in byte ordering and alignment
requirements. It is absolutely essential to handle these differences.
However, don't make any effort to cater to the possibility that an
int will be less than 32 bits. We don't support 16-bit machines
in GNU.
Similarly, don't make any effort to cater to the possibility that
long will be smaller than predefined types like size_t.
For example, the following code is ok:
printf ("size = %lu\n", (unsigned long) sizeof array);
printf ("diff = %ld\n", (long) (pointer2 - pointer1));
1989 Standard C requires this to work, and we know of only one counterexample: 64-bit programs on Microsoft Windows IA-64. We will leave it to those who want to port GNU programs to that environment to figure out how to do it.
Predefined file-size types like off_t are an exception: they are
longer than long on many platforms, so code like the above won't
work with them. One way to print an off_t value portably is to
print its digits yourself, one by one.
Don't assume that the address of an int object is also the
address of its least-significant byte. This is false on big-endian
machines. Thus, don't make the following mistake:
int c;
...
while ((c = getchar()) != EOF)
write(file_descriptor, &c, 1);
It used to be ok to not worry about the difference between pointers
and integers when passing arguments to functions. However, on most
modern 64-bit machines pointers are wider than int.
Conversely, integer types like long long int and off_t
are wider than pointers on most modern 32-bit machines. Hence it's
often better nowadays to use prototypes to define functions whose
argument types are not trivial.
In particular, if functions accept varying argument counts or types they should be declared using prototypes containing ... and defined using stdarg.h. For an example of this, please see the Gnulib error module, which declares and defines the following function:
/* Print a message with `fprintf (stderr, FORMAT, ...)';
if ERRNUM is nonzero, follow it with ": " and strerror (ERRNUM).
If STATUS is nonzero, terminate the program with `exit (STATUS)'. */
void error (int status, int errnum, const char *format, ...);
A simple way to use the Gnulib error module is to obtain the two source files error.c and error.h from the Gnulib library source code repository at http://savannah.gnu.org/cgi-bin/viewcvs/gnulib/gnulib/lib/. Here's a sample use:
#include "error.h"
#include <errno.h>
#include <stdio.h>
char *program_name = "myprogram";
FILE *
xfopen (char const *name)
{
FILE *fp = fopen (name, "r");
if (! fp)
error (1, errno, "cannot read %s", name);
return fp;
}
Avoid casting pointers to integers if you can. Such casts greatly
reduce portability, and in most programs they are easy to avoid. In the
cases where casting pointers to integers is essential—such as, a Lisp
interpreter which stores type information as well as an address in one
word—you'll have to make explicit provisions to handle different word
sizes. You will also need to make provision for systems in which the
normal range of addresses you can get from malloc starts far away
from zero.
C implementations differ substantially. Standard C reduces but does not eliminate the incompatibilities; meanwhile, many GNU packages still support pre-standard compilers because this is not hard to do. This chapter gives recommendations for how to use the more-or-less standard C library functions to avoid unnecessary loss of portability.
sprintf. It returns the number of
characters written on some systems, but not on all systems.
vfprintf is not always available.
main should be declared to return type int. It should
terminate either by calling exit or by returning the integer
status code; make sure it cannot ever return an undefined value.
Almost any declaration for a system function is wrong on some system. To minimize conflicts, leave it to the system header files to declare system functions. If the headers don't declare a function, let it remain undeclared.
While it may seem unclean to use a function without declaring it, in practice this works fine for most system library functions on the systems where this really happens; thus, the disadvantage is only theoretical. By contrast, actual declarations have frequently caused actual conflicts.
malloc or
realloc.
Most GNU programs use those functions just once, in functions
conventionally named xmalloc and xrealloc. These
functions call malloc and realloc, respectively, and
check the results.
Because xmalloc and xrealloc are defined in your program,
you can declare them in other files without any risk of type conflict.
On most systems, int is the same length as a pointer; thus, the
calls to malloc and realloc work fine. For the few
exceptional systems (mostly 64-bit machines), you can use
conditionalized declarations of malloc and
realloc—or put these declarations in configuration files
specific to those systems.
That causes less of a problem than you might think. The newer standard string functions should be avoided anyway because many systems still don't support them. The string functions you can use are these:
strcpy strncpy strcat strncat
strlen strcmp strncmp
strchr strrchr
The copy and concatenate functions work fine without a declaration as
long as you don't use their values. Using their values without a
declaration fails on systems where the width of a pointer differs from
the width of int, and perhaps in other cases. It is trivial to
avoid using their values, so do that.
The compare functions and strlen work fine without a declaration
on most systems, possibly all the ones that GNU software runs on.
You may find it necessary to declare them conditionally on a
few systems.
The search functions must be declared to return char *. Luckily,
there is no variation in the data type they return. But there is
variation in their names. Some systems give these functions the names
index and rindex; other systems use the names
strchr and strrchr. Some systems support both pairs of
names, but neither pair works on all systems.
You should pick a single pair of names and use it throughout your
program. (Nowadays, it is better to choose strchr and
strrchr for new programs, since those are the standard
names.) Declare both of those names as functions returning char
*. On systems which don't support those names, define them as macros
in terms of the other pair. For example, here is what to put at the
beginning of your file (or in a header) if you want to use the names
strchr and strrchr throughout:
#ifndef HAVE_STRCHR
#define strchr index
#endif
#ifndef HAVE_STRRCHR
#define strrchr rindex
#endif
char *strchr ();
char *strrchr ();
Here we assume that HAVE_STRCHR and HAVE_STRRCHR are
macros defined in systems where the corresponding functions exist.
One way to get them properly defined is to use Autoconf.
GNU has a library called GNU gettext that makes it easy to translate the messages in a program into various languages. You should use this library in every program. Use English for the messages as they appear in the program, and let gettext provide the way to translate them into other languages.
Using GNU gettext involves putting a call to the gettext macro
around each string that might need translation—like this:
printf (gettext ("Processing file `%s'..."));
This permits GNU gettext to replace the string "Processing file
`%s'..." with a translated version.
Once a program uses gettext, please make a point of writing calls to
gettext when you add new strings that call for translation.
Using GNU gettext in a package involves specifying a text domain name for the package. The text domain name is used to separate the translations for this package from the translations for other packages. Normally, the text domain name should be the same as the name of the package—for example, fileutils for the GNU file utilities.
To enable gettext to work well, avoid writing code that makes assumptions about the structure of words or sentences. When you want the precise text of a sentence to vary depending on the data, use two or more alternative string constants each containing a complete sentences, rather than inserting conditionalized words or phrases into a single sentence framework.
Here is an example of what not to do:
printf