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