style.9 revision 12823
1.Dd December 14, 1995
2.Dt STYLE 9
3.Os FreeBSD 2.2
4.Sh NAME
5.Nm STYLE
6.Nd "Kernel source file style guide"
7.Sh DESCRIPTION
8This file contains an example of the preferred style for kernel source
9files in the FreeBSD source tree.
10
11.Bd -literal
12/*
13 * Style guide for the 4BSD KNF (Kernel Normal Form).
14 *
15 *      @(#)style       1.14 (Berkeley) 4/28/95
16 */
17
18/*
19 * VERY important single-line comments look like this.
20 */
21
22/* Most single-line comments look like this. */
23
24/*
25 * Multi-line comments look like this.  Make them real sentences.
26 * Fill them so they look like real paragraphs.
27 */
28
29/*
30 * Kernel include files come first; normally, you'll need 
31 * <sys/types.h> OR <sys/param.h>, but not both!  <sys/types.h> 
32 * includes <sys/cdefs.h>, and it's okay to depend on that.
33 */
34#include <sys/types.h>          /* Non-local includes in brackets. */
35
36/* If it's a network program, put the network include files next. */
37#include <net/if.h>
38#include <net/if_dl.h>
39#include <net/route.h>
40#include <netinet/in.h>
41#include <protocols/rwhod.h>
42
43/*
44 * Then there's a blank line, followed by the /usr include files.
45 * The /usr include files should be sorted!
46 */
47#include <stdio.h>
48
49/*
50 * Global pathnames are defined in /usr/include/paths.h.  Pathnames 
51 * local to the program go in pathnames.h in the local directory.
52 */
53#include <paths.h>
54
55/* Then, there's a blank line, and the user include files. */
56#include "pathnames.h"          /* Local includes in double quotes. */          
57
58/*
59 * Macros are capitalized, parenthesized, and should avoid side-
60 * effects.  If they are an inline expansion of a function, the 
61 * function is defined all in lowercase, the macro has the same 
62 * name all in uppercase. If the macro needs more than a single 
63 * line, use braces.  Right-justify the backslashes, it makes it
64 * easier to read.
65 */
66#define MACRO(x, y) {                                           \e
67        variable = (x) + (y);                                   \e
68        (y) += 2;                                               \e
69}
70
71/* Enum types are capitalized. */
72enum enumtype { ONE, TWO } et;
73
74/*
75 * When declaring variables in structures, declare them sorted by use,
76 * then by size, and then by alphabetical order.  The first category
77 * normally doesn't apply, but there are exceptions.  Each one gets 
78 * its own line.  
79 * Put a tab after the first word, i.e. use 
80 *     "int^Ix;" and "struct^Ifoo *x;".
81 *
82 * Major structures should be declared at the top of the file in which 
83 * they are used, or in separate header files, if they are used in 
84 * multiple source files.  Use of the structures should be by separate
85 * declarations and should be "extern" if they are declared in a header 
86 * file.
87 */
88struct foo {
89        struct  foo *next;      /* List of active foo */
90        struct  mumble amumble; /* Comment for mumble */
91        int     bar;
92};
93struct foo *foohead;            /* Head of global foo list */
94
95/* Make the structure name match the typedef. */
96typedef struct _bar {
97        int     level;
98} BAR;
99        
100/*
101 * All functions are prototyped somewhere.
102 * 
103 * Function prototypes for private functions (i.e. functions 
104 * not used elsewhere) go at the top of the first source module.
105 *
106 * Functions used from other parts of the kernel are prototyped
107 * in the relevant include file.
108 *
109 * Only use the __P macro from the include file <sys/cdefs.h> if the
110 * source file in general is compilable with an K&R Old testament 
111 * compiler.
112 * 
113 * Only the kernel has a name associated with the types, i.e. in the 
114 * kernel use:
115 *
116 *      void function __P((int fd));
117 *
118 * in user land use:
119 *
120 *      void function __P((int));
121 */
122static char     *function __P((int, const char *));
123static void      usage __P((void));
124
125/*
126 * All major routines should have a comment briefly describing what
127 * they do.  The comment before the "main" routine should describe
128 * what the program does.
129 */
130int
131main(argc, argv)
132        int argc;
133        char *argv[];
134{
135        extern char *optarg;
136        extern int optind;
137        long num;
138        int ch;
139        char *ep;
140
141        /*
142         * For consistency, getopt should be used to parse options.
143         * Options should be sorted in the getopt call and the switch 
144         * statement, unless parts of the switch cascade.  Elements 
145         * in a switch statement that cascade should have a FALLTHROUGH 
146         * comment.  Numerical arguments should be checked for accuracy.
147         * Code that cannot be reached should have a NOTREACHED comment.
148         */
149        while ((ch = getopt(argc, argv, "abn")) != EOF)
150                switch (ch) {           /* Indent the switch. */
151                case 'a':               /* Don't indent the case. */
152                        aflag = 1;
153                        /* FALLTHROUGH */
154                case 'b':
155                        bflag = 1;
156                        break;
157                case 'n':
158                        num = strtol(optarg, &ep, 10);
159                        if (num <= 0 || *ep != '\e0')
160                                err("illegal number -- %s", optarg);
161                        break;
162                case '?':
163                default:
164                        usage();
165                        /* NOTREACHED */
166                }
167        argc -= optind;
168        argv += optind;
169
170        /*
171         * Space after keywords (while, for, return, switch).
172	 * No braces are used for control statements with zero or only 
173	 * a single statement.
174         *
175         * Forever loops are done with for's, not while's.
176         */
177        for (p = buf; *p != '\e0'; ++p);
178        for (;;)
179                stmt;
180        
181        /*
182         * Parts of a for loop may be left empty.  Don't put 
183	 * declarations inside blocks unless the routine is unusually
184	 * complicated.
185         */
186        for (; cnt < 15; cnt++) {
187                stmt1;
188                stmt2;
189        }
190
191        /* Second level indents are four spaces. */
192        while (cnt < 20)
193                z = a + really + long + statment + that + needs +
194		    two lines + gets + indented + four + spaces + on + 
195		    the + second + and + subsequent + lines.
196
197        /*
198         * Closing and opening braces go on the same line as the else.
199         * Don't add braces that aren't necessary.
200         */
201        if (test)
202                stmt;
203        else if (bar) {
204                stmt;
205                stmt;
206        } else
207                stmt;
208                
209        /* No spaces after function names. */
210        if (error = function(a1, a2))
211                exit(error);
212
213        /*
214         * Unary operators don't require spaces, binary operators do.
215	 * Don't use parenthesis unless they're required for precedence,
216	 * or the statement is really confusing without them.
217         */
218        a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
219        k = !(l & FLAGS);
220
221        /*
222         * Exits should be 0 on success, and 1 on failure.  Don't 
223	 * denote all the possible exit points, using the integers 
224	 * 1 through 300.
225         */
226        exit(0);    /* Avoid obvious comments such as "Exit 0 on success." */
227}
228
229/*
230 * If a function type is declared, it should be on a line
231 * by itself preceeding the function.
232 */
233static char *
234function(a1, a2, fl, a4)
235        int a1, a2, a4; /* Declare ints, too, don't default them. */
236        float fl;       /* List in order declared, as much as possible. */
237{
238        /*
239         * When declaring variables in functions declare them sorted 
240	 * by size, then in alphabetical order; multiple ones per line 
241	 * are okay.  Old style function declarations can go on the same
242	 * line.  ANSI style function declarations should go in the 
243	 * include file "extern.h". If a line overflows reuse the type 
244	 * keyword.
245         *
246         * DO NOT initialize variables in the declarations.
247         */
248        extern u_char one;
249        extern char two;
250        struct foo three, *four;
251        double five;
252        int *six, seven, eight();
253        char *nine, ten, eleven, twelve, thirteen, fourteen, fifteen;
254        char *overflow __P((void));
255        void *mymalloc __P((u_int));
256
257        /*
258         * Casts and sizeof's are not followed by a space.  NULL is any
259         * pointer type, and doesn't need to be cast, so use NULL instead
260         * of (struct foo *)0 or (struct foo *)NULL.  Also, test pointers
261         * against NULL, i.e. use:
262         *
263         *      (p = f()) == NULL
264         * not:
265         *      !(p = f())
266         *
267         * Don't use '!' for tests unless it's a boolean, e.g. use
268         * "if (*p == '\e0')", not "if (!*p)".
269         *
270         * Routines returning void * should not have their return 
271	 * values cast to any pointer type.
272         *
273         * Use err/warn(3), don't roll your own!
274         */
275        if ((four = malloc(sizeof(struct foo))) == NULL)
276                err(1, NULL);
277        if ((six = (int *)overflow()) == NULL)
278                errx(1, "Number overflowed.");
279        return (eight);
280}
281
282/*
283 * Don't use ANSI function declarations unless you absolutely have too,
284 * i.e. you're declaring functions with variable numbers of arguments.
285 *
286 * ANSI function return values and braces look like regular functions.
287 */
288int
289function(int a1, int a2)
290{
291        ...
292}
293
294/* Variable numbers of arguments should look like this. */
295#if __STDC__
296#include <stdarg.h>
297#else
298#include <varargs.h>
299#endif
300
301void
302#if __STDC__
303vaf(const char *fmt, ...)
304#else
305vaf(fmt, va_alist)
306        char *fmt;
307        va_dcl
308#endif
309{
310        va_list ap;
311#if __STDC__
312        va_start(ap, fmt);
313#else
314        va_start(ap);
315#endif
316        STUFF;
317
318        va_end(ap);        /* No return needed for void functions. */
319}
320
321static void
322usage()
323{       /* Insert an empty line if the function has no local variables. */
324
325        /*
326         * Use printf(3), not fputs/puts/putchar/whatever, it's faster
327	 * and usually cleaner, not to mention avoiding stupid bugs.
328         *
329         * Usage statements should look like the manual pages.  Options
330	 * w/o operands come first, in alphabetical order inside a single
331	 * set of braces.  Followed by options with operands, in 
332	 * alphabetical order, each in braces.  Followed by required 
333	 * arguments in the order they are specified, followed by optional
334	 * arguments in the order they are specified.  A bar ('|') 
335	 * separates either/or options/arguments, and multiple options/
336	 * arguments which are specified together are placed in a single
337	 * set of braces.
338         *
339         * "usage: f [-ade] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
340         * "usage: f [-a | -b] [-c [-de] [-n number]]\en"
341         */
342        (void)fprintf(stderr, "usage: f [-ab]\en");
343        exit(1);
344}
345.Ed
346.Sh HISTORY
347This man page is largely based on the src/admin/style/style file from
348the BSD 4.4-Lite2 release, with a few updates to reflect the current
349practice and desire of the FreeBSD project.
350
351
352