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