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 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
70 * Copyright (c) 1984-2025 John Q. Public
72 * Long, boring license goes here, but trimmed for brevity
76 An automatic script collects license information from the tree for
77 all comments that start in the first column with
81 to not reformat a comment that starts in the first column which is not a
82 license or copyright notice, change the dash to a star for those
84 Comments starting in columns other than the first are never
85 considered license statements.
86 Use the appropriate SPDX-License-Identifier line before the copyright.
88 After any copyright header, there is a blank line, and the
90 for non C/C++ language source files.
91 Version control system ID tags should only exist once in a file
93 Non-C/C++ source files follow the example above, while C/C++ source files
95 All VCS (version control system) revision identification in files obtained
96 from elsewhere should be maintained, including, where applicable, multiple IDs
97 showing a file's history.
98 In general, do not edit foreign IDs or their infrastructure.
99 Unless otherwise wrapped (such as
100 .Dq Li "#if defined(LIBC_SCCS)" ) ,
102 .Dq Li "#if 0 ... #endif"
103 to hide any uncompilable bits
104 and to keep the IDs out of object files.
107 in front of foreign VCS IDs if the file is renamed.
109 /* From: @(#)style 1.14 (Berkeley) 4/28/95 */
111 #include <sys/cdefs.h>
112 __FBSDID("$FreeBSD$");
115 Leave one blank line before the header files.
129 is needed, include it before other include files.
136 The remaining kernel headers should be sorted alphabetically.
138 #include <sys/types.h> /* Non-local includes in angle brackets. */
139 #include <sys/endian.h>
140 #include <sys/lock.h>
141 #include <sys/queue.h>
144 For a network program, put the network include files next.
147 #include <net/if_dl.h>
148 #include <net/route.h>
149 #include <netinet/in.h>
150 #include <protocols/rwhod.h>
153 Do not include files from
157 Leave a blank line before the next group, the
160 which should be sorted alphabetically by name.
165 Global pathnames are defined in
170 in the local directory.
175 Leave another blank line before the local include files.
177 #include "pathnames.h" /* Local includes in double quotes. */
182 or declare names in the implementation namespace except
183 for implementing application interfaces.
187 macros (ones that have side effects), and the names of macros for
188 manifest constants, are all in uppercase.
189 The expansions of expression-like macros are either a single token
190 or have outer parentheses.
191 Put a single tab character between the
194 If a macro is an inline expansion of a function, the function name is
195 all in lowercase and the macro has the same name all in uppercase.
196 .\" XXX the above conflicts with ANSI style where the names are the
197 .\" same and you #undef the macro (if any) to get the function.
198 .\" It is not followed for MALLOC(), and not very common if inline
199 .\" functions are used.
201 backslashes; it makes it easier to read.
202 If the macro encapsulates a compound statement, enclose it in a
205 so that it can safely be used in
208 Any final statement-terminating semicolon should be
209 supplied by the macro invocation rather than the macro, to make parsing easier
210 for pretty-printers and editors.
212 #define MACRO(x, y) do { \e
213 variable = (x) + (y); \e
218 When code is conditionally compiled using
222 a comment may be added following the matching
226 to permit the reader to easily discern where conditionally compiled code
228 This comment should be used only for (subjectively) long regions, regions
229 greater than 20 lines, or where a series of nested
231 may be confusing to the reader.
232 The comment should be separated from the
237 For short conditionally compiled regions, a closing comment should not be
242 should match the expression used in the corresponding
250 should match the inverse of the expression(s) used in the preceding
255 In the comments, the subexpression
259 For the purposes of comments,
260 .Dq Ic #ifndef Li FOO
262 .Dq Ic #if Li !defined(FOO) .
265 #include <sys/ktrace.h>
269 /* A large region here, or other conditional code. */
270 #else /* !COMPAT_43 */
272 #endif /* COMPAT_43 */
275 /* Yet another large region here, or other conditional code. */
276 #else /* COMPAT_43 */
278 #endif /* !COMPAT_43 */
281 The project is slowly moving to use the
283 unsigned integer identifiers of the form
285 in preference to the older
287 integer identifiers of the form
289 New code should use the former, and old code should be converted to
290 the new form if other major work is being done in that area and
291 there is no overriding reason to prefer the older
293 Like white-space commits, care should be taken in making
297 Similarly, the project is slowly moving to use the
300 in preference to the older
306 and old code may be converted if it is
308 Literal values are named
312 These are preferred to the old spellings
316 Userspace code should include
318 while kernel code should include
321 Likewise, the project is moving to using the
323 designated initializers when it makes sense to do so.
325 Enumeration values are all uppercase.
327 enum enumtype { ONE, TWO } et;
330 The use of internal_underscores in identifiers is preferred over
331 camelCase or TitleCase.
333 In declarations, do not put any whitespace between asterisks and
334 adjacent tokens, except for tokens that are identifiers related to
336 (These identifiers are the names of basic types, type
338 .Ic typedef Ns -names
339 other than the one being declared.)
340 Separate these identifiers from asterisks using a single space.
342 When declaring variables in structures, declare them sorted by use, then
343 by size (largest to smallest), and then in alphabetical order.
344 The first category normally does not apply, but there are exceptions.
345 Each one gets its own line.
346 Try to make the structure
347 readable by aligning the member names using either one or two tabs
348 depending upon your judgment.
349 You should use one tab only if it suffices to align at least 90% of
351 Names following extremely long types
352 should be separated by a single space.
354 Major structures should be declared at the top of the file in which they
355 are used, or in separate header files if they are used in multiple
357 Use of the structures should be by separate declarations
360 if they are declared in a header file.
363 struct foo *next; /* List of active foo. */
364 struct mumble amumble; /* Comment for mumble. */
365 int bar; /* Try to align the comments. */
366 struct verylongtypename *baz; /* Does not fit in 2 tabs. */
368 struct foo *foohead; /* Head of global foo list. */
373 macros rather than rolling your own lists, whenever possible.
375 the previous example would be better written:
377 #include <sys/queue.h>
380 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */
381 struct mumble amumble; /* Comment for mumble. */
382 int bar; /* Try to align the comments. */
383 struct verylongtypename *baz; /* Does not fit in 2 tabs. */
385 LIST_HEAD(, foo) foohead; /* Head of global foo list. */
388 Avoid using typedefs for structure types.
389 Typedefs are problematic because they do not properly hide their
390 underlying type; for example you need to know if the typedef is
391 the structure itself or a pointer to the structure.
392 In addition they must be declared exactly once, whereas an
393 incomplete structure type can be mentioned as many times as
395 Typedefs are difficult to use in stand-alone header files:
396 the header that defines the typedef must be included
397 before the header that uses it, or by the header that uses
398 it (which causes namespace pollution), or there must be a
399 back-door mechanism for obtaining the typedef.
401 When convention requires a
403 make its name match the struct tag.
404 Avoid typedefs ending in
406 except as specified in Standard C or by POSIX.
408 /* Make the structure name match the typedef. */
412 typedef int foo; /* This is foo. */
413 typedef const long baz; /* This is baz. */
416 All functions are prototyped somewhere.
418 Function prototypes for private functions (i.e., functions not used
419 elsewhere) go at the top of the first source module.
421 local to one source module should be declared
424 Functions used from other parts of the kernel are prototyped in the
425 relevant include file.
426 Function prototypes should be listed in a logical order, preferably
427 alphabetical unless there is a compelling reason to use a different
430 Functions that are used locally in more than one module go into a
431 separate header file, e.g.,
438 In general code can be considered
440 when it makes up about 50% or more of the file(s) involved.
442 to break precedents in the existing code and use the current
446 The kernel has a name associated with parameter types, e.g., in the kernel
449 void function(int fd);
452 In header files visible to userland applications, prototypes that are
453 visible must use either
455 names (ones beginning with an underscore)
456 or no names with the types.
457 It is preferable to use protected names.
465 void function(int _fd);
468 Prototypes may have an extra space after a tab to enable function names
471 static char *function(int _arg, const char *_arg2, struct foo *_arg3,
473 static void usage(void);
476 * All major routines should have a comment briefly describing what
477 * they do. The comment before the "main" routine should describe
478 * what the program does.
481 main(int argc, char *argv[])
490 should be used to parse options.
492 should be sorted in the
502 statement that cascade should have a
505 Numerical arguments should be checked for accuracy.
506 Code which is unreachable for non-obvious reasons may be marked /*
510 while ((ch = getopt(argc, argv, "abNn:")) != -1)
511 switch (ch) { /* Indent the switch. */
512 case 'a': /* Do not indent the case. */
513 aflag = 1; /* Indent case body one tab. */
522 num = strtol(optarg, &ep, 10);
523 if (num <= 0 || *ep != '\e0') {
524 warnx("illegal number, -n argument -- %s",
538 .Pq Ic if , while , for , return , switch .
543 are allowed for single line statements.
544 Either they are used for all single statements, or
545 they are used only where needed for clarity.
546 Usage within a function should be consistent.
547 Forever loops are done with
552 for (p = buf; *p != '\e0'; ++p)
557 z = a + really + long + statement + that + needs +
558 two + lines + gets + indented + four + spaces +
559 on + the + second + and + subsequent + lines;
566 val = realloc(val, newsize);
571 loop may be left empty.
572 Do not put declarations
573 inside blocks unless the routine is unusually complicated.
575 for (; cnt < 15; cnt++) {
581 Indentation is an 8 character tab.
582 Second level indents are four spaces.
583 If you have to wrap a long statement, put the operator at the end of the
586 while (cnt < 20 && this_variable_name_is_too_long &&
588 z = a + really + long + statement + that + needs +
589 two + lines + gets + indented + four + spaces +
590 on + the + second + and + subsequent + lines;
593 Do not add whitespace at the end of a line, and only use tabs
595 to form the indentation.
596 Do not use more spaces than a tab will produce
597 and do not use spaces in front of tabs.
599 Closing and opening braces go on the same line as the
601 Braces that are not necessary may be left out.
612 No spaces after function names.
613 Commas have a space after them.
625 error = function(a1, a2);
630 Unary operators do not require spaces, binary operators do.
631 Do not use parentheses unless they are required for precedence or unless the
632 statement is confusing without them.
633 Remember that other people may
634 confuse easier than you.
635 Do YOU understand the following?
637 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
641 Exits should be 0 on success, or 1 on failure.
644 * Avoid obvious comments such as
645 * "Exit 0 on success."
650 The function type should be on a line by itself
651 preceding the function.
652 The opening brace of the function body should be
656 function(int a1, int a2, float fl, int a4)
660 When declaring variables in functions declare them sorted by size,
661 then in alphabetical order; multiple ones per line are okay.
662 If a line overflows reuse the type keyword.
664 Be careful to not obfuscate the code by initializing variables in
666 Use this feature only thoughtfully.
667 DO NOT use function calls in initializers.
669 struct foo one, *two;
672 char *six, seven, eight, nine, ten, eleven, twelve;
677 Do not declare functions inside other functions; ANSI C says that
678 such declarations have file scope regardless of the nesting of the
680 Hiding file declarations in what appears to be a local
681 scope is undesirable and will elicit complaints from a good compiler.
685 are not followed by a space.
688 does not understand this rule.
690 are written with parenthesis always.
691 The redundant parenthesis rules do not apply to
696 is the preferred null pointer constant.
700 .Vt ( "type *" ) Ns 0
702 .Vt ( "type *" ) Ns Dv NULL
703 in contexts where the compiler knows the
704 type, e.g., in assignments.
706 .Vt ( "type *" ) Ns Dv NULL
708 in particular for all function args.
709 (Casting is essential for
710 variadic args and is necessary for other args if the function prototype
711 might not be in scope.)
712 Test pointers against
726 for tests unless it is a boolean, e.g., use:
738 should not have their return values cast
743 statements should be enclosed in parentheses.
749 do not roll your own.
751 if ((four = malloc(sizeof(struct foo))) == NULL)
752 err(1, (char *)NULL);
753 if ((six = (int *)overflow()) == NULL)
754 errx(1, "number overflowed");
759 When converting K&R style declarations to ANSI style, preserve
760 any comments about parameters.
762 Long parameter lists are wrapped with a normal four space indent.
764 Variable numbers of arguments should look like this:
769 vaf(const char *fmt, ...)
776 /* No return needed for void functions. */
782 /* Optional blank line goes here. */
785 Optionally, insert a blank line at the beginning of functions with no local
787 Older versions of this
789 document required the blank line convention, so it is widely used in existing
792 Do not insert a blank line at the beginning of functions with local variables.
793 Instead, these should have local variable declarations first, followed by one
794 blank line, followed by the first statement.
802 whatever; it is faster and usually cleaner, not
803 to mention avoiding stupid bugs.
805 Usage statements should look like the manual pages
807 The usage statement should be structured in the following order:
810 Options without operands come first,
811 in alphabetical order,
812 inside a single set of brackets
817 Options with operands come next,
818 also in alphabetical order,
819 with each option and its argument inside its own pair of brackets.
824 listed in the order they should be specified on the command line.
827 any optional arguments should be listed,
828 listed in the order they should be specified,
829 and all inside brackets.
837 and multiple options/arguments which are specified together are
838 placed in a single set of brackets.
839 .Bd -literal -offset 4n
840 "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
841 "usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
844 (void)fprintf(stderr, "usage: f [-ab]\en");
849 Note that the manual page options description should list the options in
850 pure alphabetical order.
851 That is, without regard to whether an option takes arguments or not.
852 The alphabetical ordering should take into account the case ordering
855 New core kernel code should be reasonably compliant with the
858 The guidelines for third-party maintained modules and device drivers are more
859 relaxed but at a minimum should be internally consistent with their style.
861 Stylistic changes (including whitespace changes) are hard on the source
862 repository and are to be avoided without good reason.
863 Code that is approximately
867 compliant in the repository must not diverge from compliance.
869 Whenever possible, code should be run through a code checker
870 (e.g., various static analyzers or
872 and produce minimal warnings.
874 .Bl -tag -width indent
875 .It Pa /usr/src/tools/tools/editing/freebsd.el
876 An Emacs plugin to follow the
880 .It Pa /usr/src/tools/tools/editing/freebsd.vim
881 A Vim plugin to follow the
890 .Xr style.Makefile 5 ,
893 This manual page is largely based on the
894 .Pa src/admin/style/style
897 release, with occasional updates to reflect the current practice and
901 .Pa src/admin/style/style
902 is a codification by the CSRG of the programming style of Ken Thompson and