1 .\" Copyright (c) 1995 FreeBSD Inc.
2 .\" All rights reserved.
4 .\" Redistribution and use in source and binary forms, with or without
5 .\" modification, are permitted provided that the following conditions
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.
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
25 .\" $Id: style.9,v 1.23 1999/01/30 04:17:14 julian Exp $
32 .Nd "Kernel source file style guide"
34 This file specifies the preferred style for kernel source files in the
36 source tree. It is also a guide for preferred user land code style.
37 .Bd -literal -offset 0i
39 * Style guide for the FreeBSD KNF (Kernel Normal Form).
43 * VERY important single-line comments look like this.
46 /* Most single-line comments look like this. */
49 * Multi-line comments look like this. Make them real sentences. Fill
50 * them so they look like real paragraphs.
54 Kernel include files (i.e. sys/*.h) come first; normally, you'll need
56 OR <sys/param.h>, but not both! <sys/types.h> includes <sys/cdefs.h>,
57 and it's okay to depend on that.
58 .Bd -literal -offset 0i
59 #include <sys/types.h> /* Non-local includes in brackets. */
62 If it's a network program, put the network include files next.
63 .Bd -literal -offset 0i
65 #include <net/if_dl.h>
66 #include <net/route.h>
67 #include <netinet/in.h>
68 #include <protocols/rwhod.h>
71 Then there's a blank line, followed by the /usr include files.
72 The /usr include files should be sorted!
73 .Bd -literal -offset 0i
77 Global pathnames are defined in /usr/include/paths.h. Pathnames local
78 to the program go in pathnames.h in the local directory.
79 .Bd -literal -offset 0i
83 Then, there's a blank line, and the user include files.
84 .Bd -literal -offset 0i
85 #include "pathnames.h" /* Local includes in double quotes. */
88 Macros are capitalized, parenthesized, and should avoid side-effects.
89 If they are an inline expansion of a function, the function is defined
90 all in lowercase, the macro has the same name all in uppercase. If the
91 macro needs more than a single line, use braces. Right-justify the
92 backslashes, it makes it easier to read.
93 If the macro encapsulates a compound statement, enclose it in a
96 so that it can safely be used in
99 Any final statement-terminating semicolon should be
100 supplied by the macro invocation rather than the macro, to make parsing easier
101 for pretty-printers and editors.
102 .Bd -literal -offset 0i
103 #define MACRO(x, y) do { \e
104 variable = (x) + (y); \e
109 Enumeration values are all uppercase.
110 .Bd -literal -offset 0i
111 enum enumtype { ONE, TWO } et;
114 When declaring variables in structures, declare them sorted by use, then
115 by size, and then by alphabetical order. The first category normally
116 doesn't apply, but there are exceptions. Each one gets its own line.
117 Put a tab after the first word, i.e. use
120 .Ql struct^Ifoo *x; .
122 Major structures should be declared at the top of the file in which they
123 are used, or in separate header files, if they are used in multiple
124 source files. Use of the structures should be by separate declarations
125 and should be "extern" if they are declared in a header file.
126 .Bd -literal -offset 0i
128 struct foo *next; /* List of active foo */
129 struct mumble amumble; /* Comment for mumble */
132 struct foo *foohead; /* Head of global foo list */
137 macros rather than rolling your own lists, whenever possible. Thus,
138 the previous example would be better written:
139 .Bd -literal -offset 0i
140 #include <sys/queue.h>
142 LIST_ENTRY(foo) link; /* Queue macro glue for foo lists */
143 struct mumble amumble; /* Comment for mumble */
146 LIST_HEAD(, foo) foohead; /* Head of global foo list */
149 Avoid using typedefs for structure types. This makes it impossible
150 for applications to use pointers to such a structure opaquely, which
151 is both possible and beneficial when using an ordinary struct tag.
152 When convention requires a typedef, make its name match the struct
153 tag. Avoid typedefs ending in
155 except as specified in Standard C or by
157 .Bd -literal -offset 0i
158 /* Make the structure name match the typedef. */
159 typedef struct _bar {
164 All functions are prototyped somewhere.
166 Function prototypes for private functions (i.e. functions not used
167 elsewhere) go at the top of the first source module. Functions
168 local to one source module should be declared
171 Functions used from other parts of the kernel are prototyped in the
172 relevant include file.
174 Functions that are used locally in more than one module go into a
175 separate header file, e.g.
178 Only use the __P macro from the include file <sys/cdefs.h> if the source
179 file in general is (to be) compilable with a K&R Old testament compiler.
180 Use of the __P macro in new code is discouraged, although modifications
181 to existing files should be consistent with that file's conventions.
183 In general code can be considered
185 when it makes up about 50% or more of the file[s] involved. This is enough
186 to break precedents in the existing code and use the current style guidelines.
188 The kernel has a name associated with parameter types, e.g., in the kernel
190 .Bd -literal -offset 0i
191 void function(int fd);
194 In header files visible to user land applications, prototypes that are
195 visible must use either protected names or no names with the types. It
196 is preferable to use protected names.
198 .Bd -literal -offset 0i
203 .Bd -literal -offset 0i
204 void function(int _fd);
207 Prototypes may have an extra space after a tab to enable function names
209 .Bd -literal -offset 0i
210 static char *function(int _arg, const char *_arg2, struct foo *_arg3,
212 static void usage(void);
215 * All major routines should have a comment briefly describing what
216 * they do. The comment before the "main" routine should describe
217 * what the program does.
220 main(int argc, char *argv[])
228 For consistency, getopt should be used to parse options. Options
229 should be sorted in the getopt call and the switch statement, unless
230 parts of the switch cascade. Elements in a switch statement that
231 cascade should have a FALLTHROUGH comment. Numerical arguments
232 should be checked for accuracy. Code that cannot be reached should
233 have a NOTREACHED comment.
234 .Bd -literal -offset 0i
235 while ((ch = getopt(argc, argv, "abn")) != -1)
236 switch (ch) { /* Indent the switch. */
237 case 'a': /* Don't indent the case. */
244 num = strtol(optarg, &ep, 10);
245 if (num <= 0 || *ep != '\e0')
246 err("illegal number -- %s", optarg);
258 Space after keywords (if, while, for, return, switch). No braces are
259 used for control statements with zero or only a single statement unless that
260 statement is more than a single line in which case they are permitted.
261 Forever loops are done with for's, not while's.
262 .Bd -literal -offset 0i
263 for (p = buf; *p != '\e0'; ++p)
268 z = a + really + long + statement + that + needs +
269 two lines + gets + indented + four + spaces +
270 on + the + second + and + subsequent + lines;
277 val = realloc(val, newsize);
280 Parts of a for loop may be left empty. Don't put declarations
281 inside blocks unless the routine is unusually complicated.
282 .Bd -literal -offset 0i
283 for (; cnt < 15; cnt++) {
289 Indentation is an 8 character tab.
290 Second level indents are four spaces.
291 .Bd -literal -offset 0i
293 z = a + really + long + statement + that + needs +
294 two lines + gets + indented + four + spaces +
295 on + the + second + and + subsequent + lines.
298 Do not add whitespace at the end of a line, and only use tabs then spaces
299 to form the indentation. Do not use more spaces than a tab will produce
300 and do not use spaces in front of tabs.
302 Closing and opening braces go on the same line as the else.
303 Braces that aren't necessary may be left out.
304 .Bd -literal -offset 0i
314 No spaces after function names. Commas have a space after them. No spaces
324 .Bd -literal -offset 0i
325 if (error = function(a1, a2))
329 Unary operators don't require spaces, binary operators do. Don't
330 use parentheses unless they're required for precedence, or the
331 statement is confusing without them. Remember that other people may
332 confuse easier then you. Do YOU understand the following?
333 .Bd -literal -offset 0i
334 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
338 Exits should be 0 on success, or according to the predefined
341 .Bd -literal -offset 0i
343 * Avoid obvious comments such as
344 * "Exit 0 on success."
349 The function type should be on a line by itself
350 preceding the function.
351 .Bd -literal -offset 0i
353 function(int a1, int a2, float fl, int a4)
357 When declaring variables in functions declare them sorted by size,
358 then in alphabetical order; multiple ones per line are okay.
359 Declaring functions inside functions is not recommendable, since their
360 linkage scope is always global. If a line overflows reuse the type
363 Be careful to not obfuscate the code by initializing variables in
364 the declarations. Use this feature only thoughtfully.
365 DO NOT use function calls in initializers!
366 .Bd -literal -offset 0i
367 struct foo one, *two;
370 char *six, seven, eight, nine, ten, eleven, twelve;
375 Do not declare functions inside other functions; ANSI C says that
376 such declarations have file scope regardless of the nesting of the
377 declaration. Hiding file declarations in what appears to be a local
378 scope is undesirable and will elicit complaints from a good compiler.
380 Casts and sizeof's are not followed by a space. Note that
382 does not understand this rule.
384 NULL is the preferred null pointer constant. Use NULL instead of
385 (type *)0 or (type *)NULL in contexts where the compiler knows the
386 type, e.g., in assignments. Use (type *)NULL in other contexts,
387 in particular for all function args. (Casting is essential for
388 varadic args and is necessary for other args if the function prototype
389 might not be in scope.)
391 against NULL, e.g., use:
392 .Bd -literal -offset 0i
397 .Bd -literal -offset 0i
401 Don't use '!' for tests unless it's a boolean, e.g. use
402 .Bd -literal -offset 0i
407 .Bd -literal -offset 0i
411 Routines returning void * should not have their return values cast
419 .Bd -literal -offset 0i
420 if ((four = malloc(sizeof(struct foo))) == NULL)
421 err(1, (char *)NULL);
422 if ((six = (int *)overflow()) == NULL)
423 errx(1, "Number overflowed.");
428 Old-style function declarations look like this:
429 .Bd -literal -offset 0i
431 function(a1, a2, fl, a4)
432 int a1, a2; /* Declare ints, too, don't default them. */
433 float fl; /* Beware double vs. float prototype differences. */
434 int a4; /* List in order declared. */
438 Use ANSI function declarations unless you explicitly need K&R compatibility.
440 Variable numbers of arguments should look like this.
441 .Bd -literal -offset 0i
445 vaf(const char *fmt, ...)
452 /* No return needed for void functions. */
458 /* Insert an empty line if the function has no local variables. */
463 not fputs/puts/putchar/whatever, it's faster and usually cleaner, not
464 to mention avoiding stupid bugs.
466 Usage statements should look like the manual pages. Options w/o
467 operands come first, in alphabetical order inside a single set of
468 braces. Followed by options with operands, in alphabetical order,
469 each in braces. Followed by required arguments in the order they
470 are specified, followed by optional arguments in the order they
473 separates either/or options/arguments,
474 and multiple options/arguments which are specified together are
475 placed in a single set of braces.
477 .Bd -ragged -offset 0.3i
478 "usage: f [-ade] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
479 "usage: f [-a | -b] [-c [-de] [-n number]]\en"
481 .Bd -literal -offset 0i
482 (void)fprintf(stderr, "usage: f [-ab]\en");
487 New core kernel code should be reasonably compliant with the style guides.
488 The guidelines for third-party maintained modules and device drivers are more
489 relaxed but at a minimum should be internally consistent with their style.
491 Stylistic changes (including whitespace changes) are hard on the source
492 repository and are to be avoided without good reason. Code that is
493 approximately KNF compliant in the repository must not diverge from
496 Whenever possible, code should be run through a code checker
497 (e.g., "gcc -Wall" or xlint(1)) and produce minimal warnings.
505 This man page is largely based on the src/admin/style/style file from
508 4.4-Lite2 release, with updates to reflect the current practice and