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.
39 * Style guide for FreeBSD. Based on the CSRG's KNF (Kernel Normal Form).
41 * @(#)style 1.14 (Berkeley) 4/28/95
42 * $FreeBSD: src/share/man/man9/style.9,v 1.32.2.16 2001/12/17 11:30:19 ru Exp $
46 * VERY important single-line comments look like this.
49 /* Most single-line comments look like this. */
52 * Multi-line comments look like this. Make them real sentences. Fill
53 * them so they look like real paragraphs.
57 After any copyright header, there is a blank line, and the
60 Version control system ID tags should only exist once in a file
62 Non-C/C++ source files follow the example above, while C/C++ source files
64 All VCS (version control system) revision identification from files obtained
65 from elsewhere should be maintained, including, where applicable, multiple IDs
66 showing a file's history.
67 In general, keep the IDs intact, including any
69 There is no reason to add
71 in front of foreign VCS IDs.
74 VCS IDs should be indented by a tab if in a comment.
76 #include <sys/cdefs.h>
77 __RCSID("@(#)style 1.14 (Berkeley) 4/28/95");
78 __FBSDID("$FreeBSD: src/share/man/man9/style.9,v 1.32.2.16 2001/12/17 11:30:19 ru Exp $");
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>
107 Leave a blank line before the next group, the
110 which should be sorted alphabetically by name.
115 Global pathnames are defined in
120 in the local directory.
125 Leave another blank line before the user include files.
127 #include "pathnames.h" /* Local includes in double quotes. */
132 or declare names in the implementation namespace except
133 for implementing application interfaces.
137 macros (ones that have side effects), and the names of macros for
138 manifest constants, are all in uppercase.
139 The expansions of expression-like macros are either a single token
140 or have outer parentheses.
141 Put a single tab character between the
144 If a macro is an inline expansion of a function, the function name is
145 all in lowercase and the macro has the same name all in uppercase.
146 .\" XXX the above conflicts with ANSI style where the names are the
147 .\" same and you #undef the macro (if any) to get the function.
148 .\" It is not followed for MALLOC(), and not very common if inline
149 .\" functions are used.
151 macro needs more than a single line, use braces
156 backslashes; it makes it easier to read.
157 If the macro encapsulates a compound statement, enclose it in a
160 so that it can safely be used in
163 Any final statement-terminating semicolon should be
164 supplied by the macro invocation rather than the macro, to make parsing easier
165 for pretty-printers and editors.
167 #define MACRO(x, y) do { \e
168 variable = (x) + (y); \e
173 Enumeration values are all uppercase.
175 enum enumtype { ONE, TWO } et;
178 When declaring variables in structures, declare them sorted by use, then
179 by size, and then in alphabetical order.
180 The first category normally does not apply, but there are exceptions.
181 Each one gets its own line.
182 Try to make the structure
183 readable by aligning the member names using either one or two tabs
184 depending upon your judgment.
185 You should use one tab if it suffices to align most of the member names.
186 Names following extremely long types
187 should be separated by a single space.
189 Major structures should be declared at the top of the file in which they
190 are used, or in separate header files if they are used in multiple
192 Use of the structures should be by separate declarations
195 if they are declared in a header file.
198 struct foo *next; /* List of active foo. */
199 struct mumble amumble; /* Comment for mumble. */
200 int bar; /* Try to align the comments. */
201 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
203 struct foo *foohead; /* Head of global foo list. */
208 macros rather than rolling your own lists, whenever possible.
210 the previous example would be better written:
212 #include <sys/queue.h>
215 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */
216 struct mumble amumble; /* Comment for mumble. */
217 int bar; /* Try to align the comments. */
218 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
220 LIST_HEAD(, foo) foohead; /* Head of global foo list. */
223 Avoid using typedefs for structure types. Typedefs are problematic
224 because they do not properly hide their underlying type; for example you
225 need to know if the typedef is the structure itself or a pointer to the
226 structure. In addition they must be declared exactly once, whereas an
227 incomplete structure type can be mentioned as many times as necessary.
228 Typedefs are difficult to use in stand-alone header files: the header
229 that defines the typedef must be included before the header that uses it,
230 or by the header that uses it (which causes namespace pollution), or
231 there must be a back-door mechanism for obtaining the typedef.
233 When convention requires a
235 make its name match the struct tag.
237 /* Make the structure name match the typedef. */
243 All functions are prototyped somewhere.
245 Function prototypes for private functions (i.e. functions not used
246 elsewhere) go at the top of the first source module.
248 local to one source module should be declared
250 Functions that are not exported outside of the kernel should
252 .Ic __private_extern__ .
254 Functions used from other parts of the kernel are prototyped in the
255 relevant include file.
257 Functions that are used locally in more than one module go into a
258 separate header file, e.g.\&
261 Do not use the __P macro.
263 In general code can be considered
265 when it makes up about 50% or more of the file(s) involved.
267 to break precedents in the existing code and use the current
271 The kernel has a name associated with parameter types, e.g., in the kernel
274 void function(int fd);
277 In header files visible to userland applications, prototypes that are
278 visible must use either
280 names (ones beginning with an underscore)
281 or no names with the types.
282 It is preferable to use protected names.
290 void function(int _fd);
293 Prototypes may have an extra space after a tab to enable function names
296 static char *function(int _arg, const char *_arg2, struct foo *_arg3,
298 static void usage(void);
301 * All major routines should have a comment briefly describing what
302 * they do. The comment before the "main" routine should describe
303 * what the program does.
306 main(int argc, char *argv[])
316 should be used to parse options.
318 should be sorted in the
328 statement that cascade should have a
331 Numerical arguments should be checked for accuracy.
332 Code that cannot be reached should have a
336 while ((ch = getopt(argc, argv, "abn:")) != -1)
337 switch (ch) { /* Indent the switch. */
338 case 'a': /* Don't indent the case. */
345 num = strtol(optarg, &ep, 10);
346 if (num <= 0 || *ep != '\e0') {
347 warnx("illegal number, -n argument -- %s",
362 .Pq Ic if , while , for , return , switch .
364 used for control statements with zero or only a single statement unless that
365 statement is more than a single line in which case they are permitted.
366 Forever loops are done with
371 for (p = buf; *p != '\e0'; ++p)
376 z = a + really + long + statement + that + needs +
377 two lines + gets + indented + four + spaces +
378 on + the + second + and + subsequent + lines;
385 val = realloc(val, newsize);
390 loop may be left empty.
391 Do not put declarations
392 inside blocks unless the routine is unusually complicated.
394 for (; cnt < 15; cnt++) {
400 Variable names should contain underscores to separate words. DO NOT use
403 Indentation is an 8 character tab. All code should fit in 80 columns.
404 If you have to wrap a long statement, put the operator at the end of the
407 while (cnt < 20 && this_variable_name_is_too_long &&
409 z = a + really + long + statement + that + needs +
410 two lines + gets + indented + four + spaces +
411 on + the + second + and + subsequent + lines;
414 Do not add whitespace at the end of a line, and only use tabs
416 to form the indentation.
417 Do not use more spaces than a tab will produce
418 and do not use spaces in front of tabs.
420 Closing and opening braces go on the same line as the
422 Braces that are not necessary may be left out.
433 No spaces after function names.
434 Commas have a space after them.
446 error = function(a1, a2);
451 Unary operators do not require spaces, binary operators do.
452 Do not use parentheses unless they are required for precedence or unless the
453 statement is confusing without them.
454 Remember that other people may
455 confuse easier than you.
456 Do YOU understand the following?
458 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
462 Exits should be 0 on success, or according to the predefined
467 * Avoid obvious comments such as
468 * "Exit 0 on success."
473 The function type should be on a line by itself
474 preceding the function.
477 function(int a1, int a2, float fl, int a4)
481 When declaring variables in functions declare them sorted by size,
482 then in alphabetical order; multiple ones per line are okay.
483 If a line overflows reuse the type keyword.
485 Be careful to not obfuscate the code by initializing variables in
487 Use this feature only thoughtfully.
488 DO NOT use function calls in initializers.
490 struct foo one, *two;
493 char *six, seven, eight, nine, ten, eleven, twelve;
498 Do not declare functions inside other functions; ANSI C says that
499 such declarations have file scope regardless of the nesting of the
501 Hiding file declarations in what appears to be a local
502 scope is undesirable and will elicit complaints from a good compiler.
506 are not followed by a space.
509 does not understand this rule.
511 are written with parentheses always.
514 is the preferred null pointer constant.
518 .Vt ( "type *" ) Ns 0
520 .Vt ( "type *" ) Ns Dv NULL
521 in contexts where the compiler knows the
522 type, e.g., in assignments.
524 .Vt ( "type *" ) Ns Dv NULL
526 in particular for all function args.
527 (Casting is essential for
528 variadic args and is necessary for other args if the function prototype
529 might not be in scope.)
530 Test pointers against
545 for tests unless it is a boolean, e.g. use
557 should not have their return values cast
562 statements should be enclosed in parentheses.
568 do not roll your own.
570 if ((four = malloc(sizeof(struct foo))) == NULL)
571 err(1, (char *)NULL);
572 if ((six = (int *)overflow()) == NULL)
573 errx(1, "number overflowed");
578 Use ANSI function declarations.
580 Variable numbers of arguments should look like this.
585 vaf(const char *fmt, ...)
592 /* No return needed for void functions. */
602 whatever; it is faster and usually cleaner, not
603 to mention avoiding stupid bugs.
605 Usage statements should look like the manual pages
607 The usage statement should be structured in the following order:
610 Options without operands come first,
611 in alphabetical order,
612 inside a single set of brackets
617 Options with operands come next,
618 also in alphabetical order,
619 with each option and its argument inside its own pair of brackets.
624 listed in the order they should be specified on the command line.
627 any optional arguments should be listed,
628 listed in the order they should be specified,
629 and all inside brackets.
637 and multiple options/arguments which are specified together are
638 placed in a single set of brackets.
639 .Bd -literal -offset 4n
640 "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
641 "usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
644 (void)fprintf(stderr, "usage: f [-ab]\en");
649 Note that the manual page options description should list the options in
650 pure alphabetical order.
651 That is, without regard to whether an option takes arguments or not.
652 The alphabetical ordering should take into account the case ordering
655 New core kernel code should be compliant with the
659 Stylistic changes (including whitespace changes) are hard on the source
660 repository and are to be avoided without good reason.
661 Code that is approximately
665 compliant in the repository must not diverge from compliance.
667 Code should be run through a code checker (e.g., sparse or
668 .Nm gcc Fl Wall Fl Werror
677 This man page is largely based on the
678 .Pa src/admin/style/style
681 release, with occasional updates to reflect the current practice and