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 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 DragonFly. Based on the CSRG's KNF (Kernel Normal Form).
45 * @(#)style 1.14 (Berkeley) 4/28/95
46 * $FreeBSD: src/share/man/man9/style.9,v 1.32.2.19 2002/04/14 19:28:03 asmodai Exp $
47 * $DragonFly: src/share/man/man9/style.9,v 1.10 2004/03/28 09:10:03 cpressey Exp $
51 * VERY important single-line comments look like this.
54 /* Most single-line comments look like this. */
57 * Multi-line comments look like this. Make them real sentences. Fill
58 * them so they look like real paragraphs.
62 * XXX in a comment indicates code which is incomplete, suboptimal,
63 * or otherwise deserving of further attention.
68 Version control system ID tags should only exist once in a file
70 All VCS (version control system) revision identification from files obtained
71 from elsewhere should be maintained in comments, including, where applicable,
72 multiple IDs showing a file's history.
73 In general, keep the IDs intact, including any
75 There is no reason to add
77 in front of foreign VCS IDs.
78 All VCS IDs should generally be placed in comments somewhere near the
79 top of the source, typically either before or after the copyright message.
81 Leave another blank line before the header files.
83 Kernel include files (i.e.\&
85 come first; normally, include
93 and it is okay to depend on that.
95 #include <sys/types.h> /* Non-local includes in angle brackets. */
98 For a network program, put the network include files next.
101 #include <net/if_dl.h>
102 #include <net/route.h>
103 #include <netinet/in.h>
104 #include <protocols/rwhod.h>
109 for files in the kernel.
111 Leave a blank line before the next group, the
114 which should be sorted alphabetically by name.
119 Global pathnames are defined in
124 in the local directory.
129 Leave another blank line before the user include files.
131 #include "pathnames.h" /* Local includes in double quotes. */
136 or declare names in the implementation namespace except
137 for implementing application interfaces.
141 macros (ones that have side effects), and the names of macros for
142 manifest constants, are all in uppercase.
143 The expansions of expression-like macros are either a single token
144 or have outer parentheses.
145 Put a single tab character between the
148 If a macro is an inline expansion of a function, the function name is
149 all in lowercase and the macro has the same name all in uppercase.
150 .\" XXX the above conflicts with ANSI style where the names are the
151 .\" same and you #undef the macro (if any) to get the function.
152 .\" It is not followed for MALLOC(), and not very common if inline
153 .\" functions are used.
155 macro needs more than a single line, use braces
160 backslashes; it makes it easier to read.
161 If the macro encapsulates a compound statement, enclose it in a
164 so that it can safely be used in
167 Any final statement-terminating semicolon should be
168 supplied by the macro invocation rather than the macro, to make parsing easier
169 for pretty-printers and editors.
171 #define MACRO(x, y) do { \e
172 variable = (x) + (y); \e
177 Enumeration values are all uppercase.
179 enum enumtype { ONE, TWO } et;
182 As fixed size integers the \*[Px] defined types are prefered:
183 .Bd -literal -offset indent
184 uint8_t 8 bits fixed size unsigned integer
185 uint16_t 16 bits fixed size unsigned integer
186 uint32_t 32 bits fixed size unsigned integer
187 uint64_t 64 bits fixed size unsigned integer
190 When declaring variables in structures, declare them sorted by use, then
191 by size, and then in alphabetical order.
192 The first category normally does not apply, but there are exceptions.
193 Each one gets its own line.
194 Try to make the structure
195 readable by aligning the member names using either one or two tabs
196 depending upon your judgment.
197 You should use one tab if it suffices to align most of the member names.
198 Names following extremely long types
199 should be separated by a single space.
201 Major structures should be declared at the top of the file in which they
202 are used, or in separate header files if they are used in multiple
204 Use of the structures should be by separate declarations
207 if they are declared in a header file.
210 struct foo *next; /* List of active foo. */
211 struct mumble amumble; /* Comment for mumble. */
212 int bar; /* Try to align the comments. */
213 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
215 struct foo *foohead; /* Head of global foo list. */
220 macros rather than rolling your own lists, whenever possible.
222 the previous example would be better written:
224 #include <sys/queue.h>
227 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */
228 struct mumble amumble; /* Comment for mumble. */
229 int bar; /* Try to align the comments. */
230 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
232 LIST_HEAD(, foo) foohead; /* Head of global foo list. */
235 Avoid using typedefs for structure types.
236 This makes it impossible
237 for applications to use pointers to such a structure opaquely, which
238 is both possible and beneficial when using an ordinary struct tag.
239 When convention requires a
241 make its name match the struct tag.
242 Avoid typedefs ending in
244 except as specified in Standard C or by \*[Px].
246 /* Make the structure name match the typedef. */
250 typedef int foo; /* This is foo. */
251 typedef const long baz; /* This is baz. */
254 All functions are prototyped somewhere.
256 Function prototypes for private functions (i.e. functions not used
257 elsewhere) go at the top of the first source module.
259 local to one source module should be declared
262 Functions used from other parts of the kernel are prototyped in the
263 relevant include file.
265 Functions that are used locally in more than one module go into a
266 separate header file, e.g.\&
273 macro from the include file
277 source tree is not expected to be K&R compliant.
279 Changes to existing files should be consistent with that file's conventions.
280 In general, code can be considered
282 when it makes up about 50% or more of the file(s) involved.
284 to break precedents in the existing code and use the current
288 Function prototypes for the kernel have parameter names associated
289 with parameter types. E.g., in the kernel use:
291 void function(int fd);
294 Prototypes that are visible to userland applications
295 should not include parameter names with the types, to avoid
296 possible collisions with defined macro names.
302 Prototypes may have an extra space after a tab to enable function names
305 static char *function(int _arg, const char *_arg2, struct foo *_arg3,
307 static void usage(void);
310 * All major routines should have a comment briefly describing what
311 * they do. The comment before the "main" routine should describe
312 * what the program does.
315 main(int argc, char **argv)
325 should be used to parse options.
327 should be sorted in the
337 statement that cascade should have a
339 comment, unless they contain no code of their own, as in the
341 element in the example below.
342 Numerical arguments should be checked for accuracy.
343 Code that cannot be reached should have a
347 while ((ch = getopt(argc, argv, "abn:")) != -1)
348 switch (ch) { /* Indent the switch. */
349 case 'a': /* Don't indent the case. */
356 num = strtol(optarg, &ep, 10);
357 if (num <= 0 || *ep != '\e0') {
358 warnx("illegal number, -n argument -- %s",
372 Put a single space after control statement keywords
373 .Pq Ic if , do , while , for , switch .
375 used for control statements with zero or only a single statement unless that
376 statement is more than a single line in which case they are permitted.
378 loops (loops with no test expression, which are only terminated by a
383 inside the loop body) are done with
388 for (p = buf; *p != '\e0'; ++p)
393 z = a + really + long + statement + that + needs +
394 two + lines + gets + indented + four + spaces +
395 on + the + second + and + subsequent + lines;
402 val = realloc(val, newsize);
407 loop may be left empty.
408 Do not put declarations
409 inside blocks unless the routine is unusually complicated.
411 for (; cnt < 15; cnt++) {
417 Indentation used for program block structure is an 8 character tab.
418 Second level indents used for line continuation are four spaces.
419 If you have to wrap a long statement, put the operator at the end of the
422 while (cnt < 20 && this_variable_name_is_really_far_too_long &&
424 z = a + really + long + statement + that + needs +
425 two + lines + gets + indented + four + spaces +
426 on + the + second + and + subsequent + lines;
430 Do not add whitespace at the end of a line, and only use tabs
432 to form the indentation.
433 Do not use more spaces than a tab will produce
434 and do not use spaces in front of tabs.
436 Closing and opening braces go on the same line as the
438 Braces that are not necessary may be left out, but always use braces around
439 complex or confusing sequences, for example if any part of a conditional is
440 multi-line, use braces for all parts of the conditional, and use braces
441 around multi-line substatements of loops or conditionals even if they are
442 theoretically one statement from the compiler's point of view.
461 /* THIS IS WRONG, BRACES SHOULD BE USED */
466 /* THIS IS ALSO WRONG, USE BRACSE AROUND THE OUTER CONDITIONAL */
472 Do not put spaces after function names,
477 characters, or preceding
484 But do put a space after commas and semicolons if there is
485 further text on the same line.
487 error = function(a1, a2);
492 Unary operators do not require spaces around them,
493 but binary operators (except for
498 Do not use parentheses unless they are required for precedence or unless the
499 statement is confusing without them.
500 Remember that other people may become
501 confused more easily than you.
502 Do YOU understand the following?
504 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
508 Casts are not followed by a space.
511 does not understand this rule.
512 Also, for the purposes of formatting, treat
516 as functions. In other words, they are not
517 followed by a space, and their single argument
518 should be enclosed in parentheses.
520 Exits should be 0 on success, or according to the predefined
525 * Avoid obvious comments such as
526 * "Exit 0 on success."
531 The function type should be on a line by itself
532 preceding the function.
535 function(int a1, int a2, float fl, int a4)
539 When declaring variables in functions declare them sorted by size,
540 then in alphabetical order; multiple ones per line are okay.
541 If a line overflows reuse the type keyword.
543 Be careful to not obfuscate the code by initializing variables in
545 Use this feature only thoughtfully.
546 DO NOT use function calls in initializers.
548 struct foo one, *two;
551 char *six, seven, eight, nine, ten, eleven, twelve;
556 Do not declare functions inside other functions; ANSI C says that
557 such declarations have file scope regardless of the nesting of the
559 Hiding file declarations in what appears to be a local
560 scope is undesirable and will elicit complaints from a good compiler.
563 is the preferred null pointer constant.
567 .Vt ( "type *" ) Ns 0
569 .Vt ( "type *" ) Ns Dv NULL
570 in contexts where the compiler knows the
571 type, e.g., in assignments.
573 .Vt ( "type *" ) Ns Dv NULL
575 in particular for all function args.
576 (Casting is essential for
577 variadic args and is necessary for other args if the function prototype
578 might not be in scope.)
579 Test pointers against
594 for tests unless it is a boolean, e.g. use
606 should not have their return values cast
613 do not roll your own.
615 if ((four = malloc(sizeof(struct foo))) == NULL)
616 err(1, (char *)NULL);
617 if ((six = (int *)overflow()) == NULL)
618 errx(1, "number overflowed");
623 Avoid old-style function declarations that look like this:
626 function(a1, a2, fl, a4)
627 int a1, a2; /* Declare ints, too, don't default them. */
628 float fl; /* Beware double vs. float prototype differences. */
629 int a4; /* List in order declared. */
633 Use ANSI function declarations instead.
634 Long parameter lists are wrapped so that the first parameter on each line
637 Variable numbers of arguments should look like this.
642 vaf(const char *fmt, ...)
649 /* No return needed for void functions. */
659 whatever; it is faster and usually cleaner, not
660 to mention avoiding stupid bugs.
662 Usage statements should look like the manual pages
664 The usage statement should be structured in the following order:
667 Options without operands come first,
668 in alphabetical order,
669 inside a single set of brackets
674 Options with operands come next,
675 also in alphabetical order,
676 with each option and its argument inside its own pair of brackets.
681 listed in the order they should be specified on the command line.
684 any optional arguments should be listed,
685 listed in the order they should be specified,
686 and all inside brackets.
694 and multiple options/arguments which are specified together are
695 placed in a single set of brackets.
696 .Bd -literal -offset 4n
697 "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
698 "usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
701 (void)fprintf(stderr, "usage: f [-ab]\en");
706 Note that the manual page options description should list the options in
707 pure alphabetical order.
708 That is, without regard to whether an option takes arguments or not.
709 The alphabetical ordering should take into account the case ordering
712 New core kernel code should be reasonably compliant with the
715 The guidelines for third-party maintained modules and device drivers are more
716 relaxed but at a minimum should be internally consistent with their style.
718 Stylistic changes (including whitespace changes) are hard on the source
719 repository and are to be avoided without good reason.
720 Code that is approximately
724 compliant in the repository must not diverge from compliance.
726 Whenever possible, code should be run through a code checker
731 and produce minimal warnings.
739 This man page is largely based on the
740 .Pa src/admin/style/style
743 release, with occasional updates to reflect the current practice and