2 .\" Copyright (c) 1995-2005 The FreeBSD Project
3 .\" All rights reserved.
5 .\" Redistribution and use in source and binary forms, with or without
6 .\" modification, are permitted provided that the following conditions
8 .\" 1. Redistributions of source code must retain the above copyright
9 .\" notice, this list of conditions and the following disclaimer.
10 .\" 2. Redistributions in binary form must reproduce the above copyright
11 .\" notice, this list of conditions and the following disclaimer in the
12 .\" documentation and/or other materials provided with the distribution.
14 .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 .\" ARE DISCLAIMED. IN NO EVENT SHALL [your name] OR CONTRIBUTORS BE LIABLE
18 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 .\" From: @(#)style 1.14 (Berkeley) 4/28/95
34 .Nd "kernel source file style guide"
36 This file specifies the preferred style for kernel source files in the
39 It is also a guide for the preferred userland code style.
40 Many of the style rules are implicit in the examples.
41 Be careful to check the examples before assuming that
43 is silent on an issue.
46 * Style guide for FreeBSD. Based on the CSRG's KNF (Kernel Normal Form).
48 * @(#)style 1.14 (Berkeley) 4/28/95
53 * VERY important single-line comments look like this.
56 /* Most single-line comments look like this. */
59 * Multi-line comments look like this. Make them real sentences. Fill
60 * them so they look like real paragraphs.
64 The copyright header should be a multi-line comment, with the first
65 line of the comment having a dash after the star like so:
68 * Copyright (c) 1984-2025 John Q. Public. All Rights Reserved.
70 * Long, boring license goes here, but redacted for brevity
74 An automatic script collects license information from the tree for
75 all comments that start in the first column with
79 to not reformat a comment that starts in the first column which is not a
80 license or copyright notice, change the dash to a star for those
82 Comments starting in columns other than the first are never
83 considered license statements.
85 After any copyright header, there is a blank line, and the
87 for non C/C++ language source files.
88 Version control system ID tags should only exist once in a file
90 Non-C/C++ source files follow the example above, while C/C++ source files
92 All VCS (version control system) revision identification in files obtained
93 from elsewhere should be maintained, including, where applicable, multiple IDs
94 showing a file's history.
95 In general, do not edit foreign IDs or their infrastructure.
96 Unless otherwise wrapped (such as
97 .Dq Li "#if defined(LIBC_SCCS)" ) ,
99 .Dq Li "#if 0 ... #endif"
100 to hide any uncompilable bits
101 and to keep the IDs out of object files.
104 in front of foreign VCS IDs if the file is renamed.
108 static char sccsid[] = "@(#)style 1.14 (Berkeley) 4/28/95";
109 #endif /* not lint */
112 #include <sys/cdefs.h>
113 __FBSDID("$FreeBSD$");
116 Leave another blank line before the header files.
118 Kernel include files (i.e.\&
120 come first; normally, include
128 and it is okay to depend on that.
130 #include <sys/types.h> /* Non-local includes in angle brackets. */
133 For a network program, put the network include files next.
136 #include <net/if_dl.h>
137 #include <net/route.h>
138 #include <netinet/in.h>
139 #include <protocols/rwhod.h>
144 for files in the kernel.
146 Leave a blank line before the next group, the
149 which should be sorted alphabetically by name.
154 Global pathnames are defined in
159 in the local directory.
164 Leave another blank line before the user include files.
166 #include "pathnames.h" /* Local includes in double quotes. */
171 or declare names in the implementation namespace except
172 for implementing application interfaces.
176 macros (ones that have side effects), and the names of macros for
177 manifest constants, are all in uppercase.
178 The expansions of expression-like macros are either a single token
179 or have outer parentheses.
180 Put a single tab character between the
183 If a macro is an inline expansion of a function, the function name is
184 all in lowercase and the macro has the same name all in uppercase.
185 .\" XXX the above conflicts with ANSI style where the names are the
186 .\" same and you #undef the macro (if any) to get the function.
187 .\" It is not followed for MALLOC(), and not very common if inline
188 .\" functions are used.
190 backslashes; it makes it easier to read.
191 If the macro encapsulates a compound statement, enclose it in a
194 so that it can safely be used in
197 Any final statement-terminating semicolon should be
198 supplied by the macro invocation rather than the macro, to make parsing easier
199 for pretty-printers and editors.
201 #define MACRO(x, y) do { \e
202 variable = (x) + (y); \e
207 When code is conditionally compiled using
211 a comment may be added following the matching
215 to permit the reader to easily discern where conditionally compiled code
217 This comment should be used only for (subjectively) long regions, regions
218 greater than 20 lines, or where a series of nested
220 may be confusing to the reader.
221 Exceptions may be made for cases where code is conditionally not compiled for
224 even though the uncompiled region may be small.
225 The comment should be separated from the
230 For short conditionally compiled regions, a closing comment should not be
235 should match the expression used in the corresponding
243 should match the inverse of the expression(s) used in the preceding
248 In the comments, the subexpression
252 For the purposes of comments,
253 .Dq Ic #ifndef Li FOO
255 .Dq Ic #if Li !defined(FOO) .
258 #include <sys/ktrace.h>
262 /* A large region here, or other conditional code. */
263 #else /* !COMPAT_43 */
265 #endif /* COMPAT_43 */
268 /* Yet another large region here, or other conditional code. */
269 #else /* COMPAT_43 */
271 #endif /* !COMPAT_43 */
274 The project is slowly moving to use the
276 unsigned integer identifiers of the form
278 in preference to the older
280 integer identifiers of the form
282 New code should use the former, and old code should be converted to
283 the new form if other major work is being done in that area and
284 there is no overriding reason to prefer the older
286 Like white-space commits, care should be taken in making
290 Enumeration values are all uppercase.
292 enum enumtype { ONE, TWO } et;
295 In declarations, do not put any whitespace between asterisks and
296 adjacent tokens, except for tokens that are identifiers related to
298 (These identifiers are the names of basic types, type
300 .Ic typedef Ns -names
301 other than the one being declared.)
302 Separate these identifiers from asterisks using a single space.
304 When declaring variables in structures, declare them sorted by use, then
305 by size (largest to smallest), and then in alphabetical order.
306 The first category normally does not apply, but there are exceptions.
307 Each one gets its own line.
308 Try to make the structure
309 readable by aligning the member names using either one or two tabs
310 depending upon your judgment.
311 You should use one tab only if it suffices to align at least 90% of
313 Names following extremely long types
314 should be separated by a single space.
316 Major structures should be declared at the top of the file in which they
317 are used, or in separate header files if they are used in multiple
319 Use of the structures should be by separate declarations
322 if they are declared in a header file.
325 struct foo *next; /* List of active foo. */
326 struct mumble amumble; /* Comment for mumble. */
327 int bar; /* Try to align the comments. */
328 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
330 struct foo *foohead; /* Head of global foo list. */
335 macros rather than rolling your own lists, whenever possible.
337 the previous example would be better written:
339 #include <sys/queue.h>
342 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */
343 struct mumble amumble; /* Comment for mumble. */
344 int bar; /* Try to align the comments. */
345 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
347 LIST_HEAD(, foo) foohead; /* Head of global foo list. */
350 Avoid using typedefs for structure types.
351 Typedefs are problematic because they do not properly hide their
352 underlying type; for example you need to know if the typedef is
353 the structure itself or a pointer to the structure.
354 In addition they must be declared exactly once, whereas an
355 incomplete structure type can be mentioned as many times as
357 Typedefs are difficult to use in stand-alone header files:
358 the header that defines the typedef must be included
359 before the header that uses it, or by the header that uses
360 it (which causes namespace pollution), or there must be a
361 back-door mechanism for obtaining the typedef.
363 When convention requires a
365 make its name match the struct tag.
366 Avoid typedefs ending in
368 except as specified in Standard C or by
371 /* Make the structure name match the typedef. */
375 typedef int foo; /* This is foo. */
376 typedef const long baz; /* This is baz. */
379 All functions are prototyped somewhere.
381 Function prototypes for private functions (i.e., functions not used
382 elsewhere) go at the top of the first source module.
384 local to one source module should be declared
387 Functions used from other parts of the kernel are prototyped in the
388 relevant include file.
389 Function prototypes should be listed in a logical order, preferably
390 alphabetical unless there is a compelling reason to use a different
393 Functions that are used locally in more than one module go into a
394 separate header file, e.g.\&
401 In general code can be considered
403 when it makes up about 50% or more of the file(s) involved.
405 to break precedents in the existing code and use the current
409 The kernel has a name associated with parameter types, e.g., in the kernel
412 void function(int fd);
415 In header files visible to userland applications, prototypes that are
416 visible must use either
418 names (ones beginning with an underscore)
419 or no names with the types.
420 It is preferable to use protected names.
428 void function(int _fd);
431 Prototypes may have an extra space after a tab to enable function names
434 static char *function(int _arg, const char *_arg2, struct foo *_arg3,
436 static void usage(void);
439 * All major routines should have a comment briefly describing what
440 * they do. The comment before the "main" routine should describe
441 * what the program does.
444 main(int argc, char *argv[])
453 should be used to parse options.
455 should be sorted in the
465 statement that cascade should have a
468 Numerical arguments should be checked for accuracy.
469 Code that cannot be reached should have a
473 while ((ch = getopt(argc, argv, "abNn:")) != -1)
474 switch (ch) { /* Indent the switch. */
475 case 'a': /* Don't indent the case. */
476 aflag = 1; /* Indent case body one tab. */
485 num = strtol(optarg, &ep, 10);
486 if (num <= 0 || *ep != '\e0') {
487 warnx("illegal number, -n argument -- %s",
502 .Pq Ic if , while , for , return , switch .
508 used for control statements with zero or only a single statement unless that
509 statement is more than a single line in which case they are permitted.
510 Forever loops are done with
515 for (p = buf; *p != '\e0'; ++p)
520 z = a + really + long + statement + that + needs +
521 two + lines + gets + indented + four + spaces +
522 on + the + second + and + subsequent + lines;
529 val = realloc(val, newsize);
534 loop may be left empty.
535 Do not put declarations
536 inside blocks unless the routine is unusually complicated.
538 for (; cnt < 15; cnt++) {
544 Indentation is an 8 character tab.
545 Second level indents are four spaces.
546 If you have to wrap a long statement, put the operator at the end of the
549 while (cnt < 20 && this_variable_name_is_too_long &&
551 z = a + really + long + statement + that + needs +
552 two + lines + gets + indented + four + spaces +
553 on + the + second + and + subsequent + lines;
556 Do not add whitespace at the end of a line, and only use tabs
558 to form the indentation.
559 Do not use more spaces than a tab will produce
560 and do not use spaces in front of tabs.
562 Closing and opening braces go on the same line as the
564 Braces that are not necessary may be left out.
575 No spaces after function names.
576 Commas have a space after them.
588 error = function(a1, a2);
593 Unary operators do not require spaces, binary operators do.
594 Do not use parentheses unless they are required for precedence or unless the
595 statement is confusing without them.
596 Remember that other people may
597 confuse easier than you.
598 Do YOU understand the following?
600 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
604 Exits should be 0 on success, or according to the predefined
609 * Avoid obvious comments such as
610 * "Exit 0 on success."
615 The function type should be on a line by itself
616 preceding the function.
617 The opening brace of the function body should be
621 function(int a1, int a2, float fl, int a4)
625 When declaring variables in functions declare them sorted by size,
626 then in alphabetical order; multiple ones per line are okay.
627 If a line overflows reuse the type keyword.
629 Be careful to not obfuscate the code by initializing variables in
631 Use this feature only thoughtfully.
632 DO NOT use function calls in initializers.
634 struct foo one, *two;
637 char *six, seven, eight, nine, ten, eleven, twelve;
642 Do not declare functions inside other functions; ANSI C says that
643 such declarations have file scope regardless of the nesting of the
645 Hiding file declarations in what appears to be a local
646 scope is undesirable and will elicit complaints from a good compiler.
650 are not followed by a space.
653 does not understand this rule.
655 are written with parenthesis always.
656 The redundant parenthesis rules do not apply to
661 is the preferred null pointer constant.
665 .Vt ( "type *" ) Ns 0
667 .Vt ( "type *" ) Ns Dv NULL
668 in contexts where the compiler knows the
669 type, e.g., in assignments.
671 .Vt ( "type *" ) Ns Dv NULL
673 in particular for all function args.
674 (Casting is essential for
675 variadic args and is necessary for other args if the function prototype
676 might not be in scope.)
677 Test pointers against
692 for tests unless it is a boolean, e.g.\& use:
704 should not have their return values cast
709 statements should be enclosed in parentheses.
715 do not roll your own.
717 if ((four = malloc(sizeof(struct foo))) == NULL)
718 err(1, (char *)NULL);
719 if ((six = (int *)overflow()) == NULL)
720 errx(1, "number overflowed");
725 Old-style function declarations look like this:
728 function(a1, a2, fl, a4)
729 int a1, a2; /* Declare ints, too, don't default them. */
730 float fl; /* Beware double vs. float prototype differences. */
731 int a4; /* List in order declared. */
735 Use ANSI function declarations unless you explicitly need K&R compatibility.
736 Long parameter lists are wrapped with a normal four space indent.
738 Variable numbers of arguments should look like this:
743 vaf(const char *fmt, ...)
750 /* No return needed for void functions. */
756 /* Insert an empty line if the function has no local variables. */
765 whatever; it is faster and usually cleaner, not
766 to mention avoiding stupid bugs.
768 Usage statements should look like the manual pages
770 The usage statement should be structured in the following order:
773 Options without operands come first,
774 in alphabetical order,
775 inside a single set of brackets
780 Options with operands come next,
781 also in alphabetical order,
782 with each option and its argument inside its own pair of brackets.
787 listed in the order they should be specified on the command line.
790 any optional arguments should be listed,
791 listed in the order they should be specified,
792 and all inside brackets.
800 and multiple options/arguments which are specified together are
801 placed in a single set of brackets.
802 .Bd -literal -offset 4n
803 "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
804 "usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
807 (void)fprintf(stderr, "usage: f [-ab]\en");
812 Note that the manual page options description should list the options in
813 pure alphabetical order.
814 That is, without regard to whether an option takes arguments or not.
815 The alphabetical ordering should take into account the case ordering
818 New core kernel code should be reasonably compliant with the
821 The guidelines for third-party maintained modules and device drivers are more
822 relaxed but at a minimum should be internally consistent with their style.
824 Stylistic changes (including whitespace changes) are hard on the source
825 repository and are to be avoided without good reason.
826 Code that is approximately
830 compliant in the repository must not diverge from compliance.
832 Whenever possible, code should be run through a code checker
837 and produce minimal warnings.
846 This manual page is largely based on the
847 .Pa src/admin/style/style
850 release, with occasional updates to reflect the current practice and