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