1 .\" Copyright (c) 1995-2001 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
31 .Nd "kernel source file style guide"
33 This file specifies the preferred style for kernel source files in the
36 It is also a guide for the preferred userland code style.
37 Many of the style rules are implicit in the examples.
38 Be careful to check the examples before assuming that
40 is silent on an issue.
43 * Style guide for FreeBSD. Based on the CSRG's KNF (Kernel Normal Form).
45 * @(#)style 1.14 (Berkeley) 4/28/95
50 * VERY important single-line comments look like this.
53 /* Most single-line comments look like this. */
56 * Multi-line comments look like this. Make them real sentences. Fill
57 * them so they look like real paragraphs.
61 After any copyright header, there is a blank line, and the
64 Version control system ID tags should only exist once in a file
66 Non-C/C++ source files follow the example above, while C/C++ source files
68 All VCS (version control system) revision identification in files obtained
69 from elsewhere should be maintained, including, where applicable, multiple IDs
70 showing a file's history.
71 In general, do not edit foreign IDs or their infrastructure.
72 Unless otherwise wrapped (such as
73 .Dq Li "#if defined(LIBC_SCCS)" ) ,
75 .Dq Li "#if 0 ... #endif"
76 to hide any uncompilable bits
77 and to keep the IDs out of object files.
80 in front of foreign VCS IDs if the file is renamed.
84 static char sccsid[] = "@(#)style 1.14 (Berkeley) 4/28/95";
88 #include <sys/cdefs.h>
89 __FBSDID("$FreeBSD$");
92 Leave another blank line before the header files.
94 Kernel include files (i.e.\&
96 come first; normally, include
104 and it is okay to depend on that.
106 #include <sys/types.h> /* Non-local includes in angle brackets. */
109 For a network program, put the network include files next.
112 #include <net/if_dl.h>
113 #include <net/route.h>
114 #include <netinet/in.h>
115 #include <protocols/rwhod.h>
120 for files in the kernel.
122 Leave a blank line before the next group, the
125 which should be sorted alphabetically by name.
130 Global pathnames are defined in
135 in the local directory.
140 Leave another blank line before the user include files.
142 #include "pathnames.h" /* Local includes in double quotes. */
147 or declare names in the implementation namespace except
148 for implementing application interfaces.
152 macros (ones that have side effects), and the names of macros for
153 manifest constants, are all in uppercase.
154 The expansions of expression-like macros are either a single token
155 or have outer parentheses.
156 Put a single tab character between the
159 If a macro is an inline expansion of a function, the function name is
160 all in lowercase and the macro has the same name all in uppercase.
161 .\" XXX the above conflicts with ANSI style where the names are the
162 .\" same and you #undef the macro (if any) to get the function.
163 .\" It is not followed for MALLOC(), and not very common if inline
164 .\" functions are used.
166 backslashes; it makes it easier to read.
167 If the macro encapsulates a compound statement, enclose it in a
170 so that it can safely be used in
173 Any final statement-terminating semicolon should be
174 supplied by the macro invocation rather than the macro, to make parsing easier
175 for pretty-printers and editors.
177 #define MACRO(x, y) do { \e
178 variable = (x) + (y); \e
183 When code is conditionally compiled using
187 a comment may be added following the matching
191 to permit the reader to easily discern where conditionally compiled code
193 This comment should be used only for (subjectively) long regions, regions
194 greater than 20 lines, or where a series of nested
196 may be confusing to the reader.
197 Exceptions may be made for cases where code is conditionally not compiled for
200 even though the uncompiled region may be small.
201 The comment should be separated from the
206 For short conditionally compiled regions, a closing comment should not be
211 should match the expression used in the corresponding
219 should match the inverse of the expression(s) used in the preceding
224 In the comments, the subexpression
228 For the purposes of comments,
229 .Dq Ic #ifndef Li FOO
231 .Dq Ic #if Li !defined(FOO) .
234 #include <sys/ktrace.h>
238 /* A large region here, or other conditional code. */
239 #else /* !COMPAT_43 */
241 #endif /* COMPAT_43 */
244 /* Yet another large region here, or other conditional code. */
245 #else /* COMPAT_43 */
247 #endif /* !COMPAT_43 */
250 The project is slowly moving to use the
252 unsigned integer identifiers of the form
254 in preference to the older
256 integer identifiers of the form
258 New code should use the former, and old code should be converted to
259 the new form if other major work is being done in that area and
260 there is no overriding reason to prefer the older
262 Like white-space commits, care should be taken in making
266 Enumeration values are all uppercase.
268 enum enumtype { ONE, TWO } et;
271 In declarations, do not put any whitespace between asterisks and
272 adjacent tokens, except for tokens that are identifiers related to
274 (These identifiers are the names of basic types, type
276 .Ic typedef Ns -names
277 other than the one being declared.)
278 Separate these identifiers from asterisks using a single space.
280 When declaring variables in structures, declare them sorted by use, then
281 by size, and then in alphabetical order.
282 The first category normally does not apply, but there are exceptions.
283 Each one gets its own line.
284 Try to make the structure
285 readable by aligning the member names using either one or two tabs
286 depending upon your judgment.
287 You should use one tab only if it suffices to align at least 90% of
289 Names following extremely long types
290 should be separated by a single space.
292 Major structures should be declared at the top of the file in which they
293 are used, or in separate header files if they are used in multiple
295 Use of the structures should be by separate declarations
298 if they are declared in a header file.
301 struct foo *next; /* List of active foo. */
302 struct mumble amumble; /* Comment for mumble. */
303 int bar; /* Try to align the comments. */
304 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
306 struct foo *foohead; /* Head of global foo list. */
311 macros rather than rolling your own lists, whenever possible.
313 the previous example would be better written:
315 #include <sys/queue.h>
318 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */
319 struct mumble amumble; /* Comment for mumble. */
320 int bar; /* Try to align the comments. */
321 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
323 LIST_HEAD(, foo) foohead; /* Head of global foo list. */
326 Avoid using typedefs for structure types.
327 Typedefs are problematic because they do not properly hide their
328 underlying type; for example you need to know if the typedef is
329 the structure itself or a pointer to the structure.
330 In addition they must be declared exactly once, whereas an
331 incomplete structure type can be mentioned as many times as
333 Typedefs are difficult to use in stand-alone header files:
334 the header that defines the typedef must be included
335 before the header that uses it, or by the header that uses
336 it (which causes namespace pollution), or there must be a
337 back-door mechanism for obtaining the typedef.
339 When convention requires a
341 make its name match the struct tag.
342 Avoid typedefs ending in
344 except as specified in Standard C or by
347 /* Make the structure name match the typedef. */
351 typedef int foo; /* This is foo. */
352 typedef const long baz; /* This is baz. */
355 All functions are prototyped somewhere.
357 Function prototypes for private functions (i.e., functions not used
358 elsewhere) go at the top of the first source module.
360 local to one source module should be declared
363 Functions used from other parts of the kernel are prototyped in the
364 relevant include file.
365 Function prototypes should be listed in a logical order, preferably
366 alphabetical unless there is a compelling reason to use a different
369 Functions that are used locally in more than one module go into a
370 separate header file, e.g.\&
377 In general code can be considered
379 when it makes up about 50% or more of the file(s) involved.
381 to break precedents in the existing code and use the current
385 The kernel has a name associated with parameter types, e.g., in the kernel
388 void function(int fd);
391 In header files visible to userland applications, prototypes that are
392 visible must use either
394 names (ones beginning with an underscore)
395 or no names with the types.
396 It is preferable to use protected names.
404 void function(int _fd);
407 Prototypes may have an extra space after a tab to enable function names
410 static char *function(int _arg, const char *_arg2, struct foo *_arg3,
412 static void usage(void);
415 * All major routines should have a comment briefly describing what
416 * they do. The comment before the "main" routine should describe
417 * what the program does.
420 main(int argc, char *argv[])
429 should be used to parse options.
431 should be sorted in the
441 statement that cascade should have a
444 Numerical arguments should be checked for accuracy.
445 Code that cannot be reached should have a
449 while ((ch = getopt(argc, argv, "abNn:")) != -1)
450 switch (ch) { /* Indent the switch. */
451 case 'a': /* Don't indent the case. */
461 num = strtol(optarg, &ep, 10);
462 if (num <= 0 || *ep != '\e0') {
463 warnx("illegal number, -n argument -- %s",
478 .Pq Ic if , while , for , return , switch .
484 used for control statements with zero or only a single statement unless that
485 statement is more than a single line in which case they are permitted.
486 Forever loops are done with
491 for (p = buf; *p != '\e0'; ++p)
496 z = a + really + long + statement + that + needs +
497 two + lines + gets + indented + four + spaces +
498 on + the + second + and + subsequent + lines;
505 val = realloc(val, newsize);
510 loop may be left empty.
511 Do not put declarations
512 inside blocks unless the routine is unusually complicated.
514 for (; cnt < 15; cnt++) {
520 Indentation is an 8 character tab.
521 Second level indents are four spaces.
522 If you have to wrap a long statement, put the operator at the end of the
525 while (cnt < 20 && this_variable_name_is_too_long &&
527 z = a + really + long + statement + that + needs +
528 two + lines + gets + indented + four + spaces +
529 on + the + second + and + subsequent + lines;
532 Do not add whitespace at the end of a line, and only use tabs
534 to form the indentation.
535 Do not use more spaces than a tab will produce
536 and do not use spaces in front of tabs.
538 Closing and opening braces go on the same line as the
540 Braces that are not necessary may be left out.
551 No spaces after function names.
552 Commas have a space after them.
564 error = function(a1, a2);
569 Unary operators do not require spaces, binary operators do.
570 Do not use parentheses unless they are required for precedence or unless the
571 statement is confusing without them.
572 Remember that other people may
573 confuse easier than you.
574 Do YOU understand the following?
576 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
580 Exits should be 0 on success, or according to the predefined
585 * Avoid obvious comments such as
586 * "Exit 0 on success."
591 The function type should be on a line by itself
592 preceding the function.
593 The opening brace of the function body should be
597 function(int a1, int a2, float fl, int a4)
601 When declaring variables in functions declare them sorted by size,
602 then in alphabetical order; multiple ones per line are okay.
603 If a line overflows reuse the type keyword.
605 Be careful to not obfuscate the code by initializing variables in
607 Use this feature only thoughtfully.
608 DO NOT use function calls in initializers.
610 struct foo one, *two;
613 char *six, seven, eight, nine, ten, eleven, twelve;
618 Do not declare functions inside other functions; ANSI C says that
619 such declarations have file scope regardless of the nesting of the
621 Hiding file declarations in what appears to be a local
622 scope is undesirable and will elicit complaints from a good compiler.
626 are not followed by a space.
629 does not understand this rule.
631 are written with parenthesis always.
632 The redundant parenthesis rules do not apply to
637 is the preferred null pointer constant.
641 .Vt ( "type *" ) Ns 0
643 .Vt ( "type *" ) Ns Dv NULL
644 in contexts where the compiler knows the
645 type, e.g., in assignments.
647 .Vt ( "type *" ) Ns Dv NULL
649 in particular for all function args.
650 (Casting is essential for
651 variadic args and is necessary for other args if the function prototype
652 might not be in scope.)
653 Test pointers against
668 for tests unless it is a boolean, e.g.\& use
680 should not have their return values cast
685 statements should be enclosed in parentheses.
691 do not roll your own.
693 if ((four = malloc(sizeof(struct foo))) == NULL)
694 err(1, (char *)NULL);
695 if ((six = (int *)overflow()) == NULL)
696 errx(1, "number overflowed");
701 Old-style function declarations look like this:
704 function(a1, a2, fl, a4)
705 int a1, a2; /* Declare ints, too, don't default them. */
706 float fl; /* Beware double vs. float prototype differences. */
707 int a4; /* List in order declared. */
711 Use ANSI function declarations unless you explicitly need K&R compatibility.
712 Long parameter lists are wrapped with a normal four space indent.
714 Variable numbers of arguments should look like this.
719 vaf(const char *fmt, ...)
726 /* No return needed for void functions. */
732 /* Insert an empty line if the function has no local variables. */
741 whatever; it is faster and usually cleaner, not
742 to mention avoiding stupid bugs.
744 Usage statements should look like the manual pages
746 The usage statement should be structured in the following order:
749 Options without operands come first,
750 in alphabetical order,
751 inside a single set of brackets
756 Options with operands come next,
757 also in alphabetical order,
758 with each option and its argument inside its own pair of brackets.
763 listed in the order they should be specified on the command line.
766 any optional arguments should be listed,
767 listed in the order they should be specified,
768 and all inside brackets.
776 and multiple options/arguments which are specified together are
777 placed in a single set of brackets.
778 .Bd -literal -offset 4n
779 "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
780 "usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
783 (void)fprintf(stderr, "usage: f [-ab]\en");
788 Note that the manual page options description should list the options in
789 pure alphabetical order.
790 That is, without regard to whether an option takes arguments or not.
791 The alphabetical ordering should take into account the case ordering
794 New core kernel code should be reasonably compliant with the
797 The guidelines for third-party maintained modules and device drivers are more
798 relaxed but at a minimum should be internally consistent with their style.
800 Stylistic changes (including whitespace changes) are hard on the source
801 repository and are to be avoided without good reason.
802 Code that is approximately
806 compliant in the repository must not diverge from compliance.
808 Whenever possible, code should be run through a code checker
813 and produce minimal warnings.
822 This man page is largely based on the
823 .Pa src/admin/style/style
826 release, with occasional updates to reflect the current practice and