1.\" Copyright (c) 1995-2001 FreeBSD Inc. 2.\" All rights reserved. 3.\" 4.\" Redistribution and use in source and binary forms, with or without 5.\" modification, are permitted provided that the following conditions 6.\" are met: 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. 12.\" 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 23.\" SUCH DAMAGE. 24.\" 25.\" 26.Dd December 7, 2001 27.Dt STYLE 9 28.Os 29.Sh NAME 30.Nm style 31.Nd "kernel source file style guide" 32.Sh DESCRIPTION 33This file specifies the preferred style for kernel source files in the 34.Fx 35source tree. 36It is also a guide for the preferred userland code style. 37Many of the style rules are implicit in the examples. 38Be careful to check the examples before assuming that 39.Nm 40is silent on an issue. 41.Bd -literal 42/* 43 * Style guide for FreeBSD. Based on the CSRG's KNF (Kernel Normal Form). 44 * 45 * @(#)style 1.14 (Berkeley) 4/28/95
| 1.\" Copyright (c) 1995-2001 FreeBSD Inc. 2.\" All rights reserved. 3.\" 4.\" Redistribution and use in source and binary forms, with or without 5.\" modification, are permitted provided that the following conditions 6.\" are met: 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. 12.\" 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 23.\" SUCH DAMAGE. 24.\" 25.\" 26.Dd December 7, 2001 27.Dt STYLE 9 28.Os 29.Sh NAME 30.Nm style 31.Nd "kernel source file style guide" 32.Sh DESCRIPTION 33This file specifies the preferred style for kernel source files in the 34.Fx 35source tree. 36It is also a guide for the preferred userland code style. 37Many of the style rules are implicit in the examples. 38Be careful to check the examples before assuming that 39.Nm 40is silent on an issue. 41.Bd -literal 42/* 43 * Style guide for FreeBSD. Based on the CSRG's KNF (Kernel Normal Form). 44 * 45 * @(#)style 1.14 (Berkeley) 4/28/95
|
46 * $FreeBSD: head/share/man/man9/style.9 87858 2001-12-14 09:22:34Z ru $
| 46 * $FreeBSD: head/share/man/man9/style.9 88545 2001-12-27 20:05:47Z alfred $
|
47 */ 48 49/* 50 * VERY important single-line comments look like this. 51 */ 52 53/* Most single-line comments look like this. */ 54 55/* 56 * Multi-line comments look like this. Make them real sentences. Fill 57 * them so they look like real paragraphs. 58 */ 59.Ed 60.Pp 61After any copyright header, there is a blank line, and the 62.Va rcsid 63for source files. 64Version control system ID tags should only exist once in a file 65(unlike this one). 66Non-C/C++ source files follow the example above, while C/C++ source files 67follow the one below. 68All VCS (version control system) revision identification from files obtained 69from elsewhere should be maintained, including, where applicable, multiple IDs 70showing a file's history. 71In general, keep the IDs intact, including any 72.So Li $ Sc Ns s . 73There is no reason to add 74.Qq Li "From" 75in front of foreign VCS IDs. 76Most 77.No non- Ns Fx 78VCS IDs should be indented by a tab if in a comment. 79.Bd -literal 80#include <sys/cdefs.h> 81__RCSID("@(#)style 1.14 (Berkeley) 4/28/95");
| 47 */ 48 49/* 50 * VERY important single-line comments look like this. 51 */ 52 53/* Most single-line comments look like this. */ 54 55/* 56 * Multi-line comments look like this. Make them real sentences. Fill 57 * them so they look like real paragraphs. 58 */ 59.Ed 60.Pp 61After any copyright header, there is a blank line, and the 62.Va rcsid 63for source files. 64Version control system ID tags should only exist once in a file 65(unlike this one). 66Non-C/C++ source files follow the example above, while C/C++ source files 67follow the one below. 68All VCS (version control system) revision identification from files obtained 69from elsewhere should be maintained, including, where applicable, multiple IDs 70showing a file's history. 71In general, keep the IDs intact, including any 72.So Li $ Sc Ns s . 73There is no reason to add 74.Qq Li "From" 75in front of foreign VCS IDs. 76Most 77.No non- Ns Fx 78VCS IDs should be indented by a tab if in a comment. 79.Bd -literal 80#include <sys/cdefs.h> 81__RCSID("@(#)style 1.14 (Berkeley) 4/28/95");
|
82__FBSDID("$FreeBSD: head/share/man/man9/style.9 87858 2001-12-14 09:22:34Z ru $");
| 82__FBSDID("$FreeBSD: head/share/man/man9/style.9 88545 2001-12-27 20:05:47Z alfred $");
|
83.Ed 84.Pp 85Leave another blank line before the header files. 86.Pp 87Kernel include files (i.e.\& 88.Pa sys/*.h ) 89come first; normally, include 90.Aq Pa sys/types.h 91OR 92.Aq Pa sys/param.h , 93but not both. 94.Aq Pa sys/types.h 95includes 96.Aq Pa sys/cdefs.h , 97and it is okay to depend on that. 98.Bd -literal 99#include <sys/types.h> /* Non-local includes in angle brackets. */ 100.Ed 101.Pp 102For a network program, put the network include files next. 103.Bd -literal 104#include <net/if.h> 105#include <net/if_dl.h> 106#include <net/route.h> 107#include <netinet/in.h> 108#include <protocols/rwhod.h> 109.Ed 110.Pp 111Do not use files in 112.Pa /usr/include 113for files in the kernel. 114.Pp 115Leave a blank line before the next group, the 116.Pa /usr 117include files, 118which should be sorted alphabetically by name. 119.Bd -literal 120#include <stdio.h> 121.Ed 122.Pp 123Global pathnames are defined in 124.Aq Pa paths.h . 125Pathnames local 126to the program go in 127.Qq Pa pathnames.h 128in the local directory. 129.Bd -literal 130#include <paths.h> 131.Ed 132.Pp 133Leave another blank line before the user include files. 134.Bd -literal 135#include "pathnames.h" /* Local includes in double quotes. */ 136.Ed 137.Pp 138Do not 139.Ic #define 140or declare names in the implementation namespace except 141for implementing application interfaces. 142.Pp 143The names of 144.Dq unsafe 145macros (ones that have side effects), and the names of macros for 146manifest constants, are all in uppercase. 147The expansions of expression-like macros are either a single token 148or have outer parentheses. 149Put a single tab character between the 150.Ic #define 151and the macro name. 152If a macro is an inline expansion of a function, the function name is 153all in lowercase and the macro has the same name all in uppercase. 154.\" XXX the above conflicts with ANSI style where the names are the 155.\" same and you #undef the macro (if any) to get the function. 156.\" It is not followed for MALLOC(), and not very common if inline 157.\" functions are used. 158If a 159macro needs more than a single line, use braces 160.Ql ( \&{ 161and 162.Ql \&} ) . 163Right-justify the 164backslashes; it makes it easier to read. 165If the macro encapsulates a compound statement, enclose it in a 166.Ic do 167loop, 168so that it can safely be used in 169.Ic if 170statements. 171Any final statement-terminating semicolon should be 172supplied by the macro invocation rather than the macro, to make parsing easier 173for pretty-printers and editors. 174.Bd -literal 175#define MACRO(x, y) do { \e 176 variable = (x) + (y); \e 177 (y) += 2; \e 178} while(0) 179.Ed 180.Pp 181Enumeration values are all uppercase. 182.Bd -literal 183enum enumtype { ONE, TWO } et; 184.Ed 185.Pp 186When declaring variables in structures, declare them sorted by use, then 187by size, and then in alphabetical order. 188The first category normally does not apply, but there are exceptions. 189Each one gets its own line. 190Try to make the structure 191readable by aligning the member names using either one or two tabs 192depending upon your judgment. 193You should use one tab if it suffices to align most of the member names. 194Names following extremely long types 195should be separated by a single space. 196.Pp 197Major structures should be declared at the top of the file in which they 198are used, or in separate header files if they are used in multiple 199source files. 200Use of the structures should be by separate declarations 201and should be 202.Ic extern 203if they are declared in a header file. 204.Bd -literal 205struct foo { 206 struct foo *next; /* List of active foo. */ 207 struct mumble amumble; /* Comment for mumble. */ 208 int bar; /* Try to align the comments. */ 209 struct verylongtypename *baz; /* Won't fit in 2 tabs. */ 210}; 211struct foo *foohead; /* Head of global foo list. */ 212.Ed 213.Pp 214Use 215.Xr queue 3 216macros rather than rolling your own lists, whenever possible. 217Thus, 218the previous example would be better written: 219.Bd -literal 220#include <sys/queue.h> 221 222struct foo { 223 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */ 224 struct mumble amumble; /* Comment for mumble. */ 225 int bar; /* Try to align the comments. */ 226 struct verylongtypename *baz; /* Won't fit in 2 tabs. */ 227}; 228LIST_HEAD(, foo) foohead; /* Head of global foo list. */ 229.Ed 230.Pp 231Avoid using typedefs for structure types. 232This makes it impossible 233for applications to use pointers to such a structure opaquely, which 234is both possible and beneficial when using an ordinary struct tag. 235When convention requires a 236.Ic typedef , 237make its name match the struct tag. 238Avoid typedefs ending in 239.Dq Li _t , 240except as specified in Standard C or by \*[Px]. 241.Bd -literal 242/* Make the structure name match the typedef. */ 243typedef struct bar { 244 int level; 245} BAR; 246typedef int foo; /* This is foo. */ 247typedef const long baz; /* This is baz. */ 248.Ed 249.Pp 250All functions are prototyped somewhere. 251.Pp 252Function prototypes for private functions (i.e. functions not used 253elsewhere) go at the top of the first source module. 254Functions 255local to one source module should be declared 256.Ic static . 257.Pp 258Functions used from other parts of the kernel are prototyped in the 259relevant include file. 260.Pp 261Functions that are used locally in more than one module go into a 262separate header file, e.g.\& 263.Qq Pa extern.h . 264.Pp 265Only use the 266.Dv __P 267macro from the include file 268.Aq Pa sys/cdefs.h 269if the source 270file in general is (to be) compilable with a K&R Old Testament compiler. 271Use of the 272.Dv __P 273macro in new code is discouraged, although modifications 274to existing files should be consistent with that file's conventions. 275.Pp 276In general code can be considered 277.Dq "new code" 278when it makes up about 50% or more of the file(s) involved. 279This is enough 280to break precedents in the existing code and use the current 281.Nm 282guidelines. 283.Pp 284The kernel has a name associated with parameter types, e.g., in the kernel 285use: 286.Bd -literal 287void function(int fd); 288.Ed 289.Pp 290In header files visible to userland applications, prototypes that are 291visible must use either 292.Dq protected 293names (ones beginning with an underscore) 294or no names with the types. 295It is preferable to use protected names. 296E.g., use: 297.Bd -literal 298void function(int); 299.Ed 300.Pp 301or: 302.Bd -literal 303void function(int _fd); 304.Ed 305.Pp 306Prototypes may have an extra space after a tab to enable function names 307to line up: 308.Bd -literal 309static char *function(int _arg, const char *_arg2, struct foo *_arg3, 310 struct bar *_arg4); 311static void usage(void); 312 313/* 314 * All major routines should have a comment briefly describing what 315 * they do. The comment before the "main" routine should describe 316 * what the program does. 317 */ 318int 319main(int argc, char *argv[]) 320{ 321 long num; 322 int ch; 323 char *ep; 324 325.Ed 326.Pp 327For consistency, 328.Xr getopt 3 329should be used to parse options. 330Options 331should be sorted in the 332.Xr getopt 3 333call and the 334.Ic switch 335statement, unless 336parts of the 337.Ic switch 338cascade. 339Elements in a 340.Ic switch 341statement that cascade should have a 342.Li FALLTHROUGH 343comment. 344Numerical arguments should be checked for accuracy. 345Code that cannot be reached should have a 346.Li NOTREACHED 347comment. 348.Bd -literal 349 while ((ch = getopt(argc, argv, "abn:")) != -1) 350 switch (ch) { /* Indent the switch. */ 351 case 'a': /* Don't indent the case. */ 352 aflag = 1; 353 /* FALLTHROUGH */ 354 case 'b': 355 bflag = 1; 356 break; 357 case 'n': 358 num = strtol(optarg, &ep, 10); 359 if (num <= 0 || *ep != '\e0') { 360 warnx("illegal number, -n argument -- %s", 361 optarg); 362 usage(); 363 } 364 break; 365 case '?': 366 default: 367 usage(); 368 /* NOTREACHED */ 369 } 370 argc -= optind; 371 argv += optind; 372.Ed 373.Pp 374Space after keywords 375.Pq Ic if , while , for , return , switch . 376No braces are 377used for control statements with zero or only a single statement unless that 378statement is more than a single line in which case they are permitted. 379Forever loops are done with 380.Ic for Ns 's , 381not 382.Ic while Ns 's . 383.Bd -literal 384 for (p = buf; *p != '\e0'; ++p) 385 ; /* nothing */ 386 for (;;) 387 stmt; 388 for (;;) { 389 z = a + really + long + statement + that + needs + 390 two lines + gets + indented + four + spaces + 391 on + the + second + and + subsequent + lines; 392 } 393 for (;;) { 394 if (cond) 395 stmt; 396 } 397 if (val != NULL) 398 val = realloc(val, newsize); 399.Ed 400.Pp 401Parts of a 402.Ic for 403loop may be left empty. 404Do not put declarations 405inside blocks unless the routine is unusually complicated. 406.Bd -literal 407 for (; cnt < 15; cnt++) { 408 stmt1; 409 stmt2; 410 } 411.Ed 412.Pp 413Indentation is an 8 character tab. 414Second level indents are four spaces. 415If you have to wrap a long statement, put the operator at the end of the 416line. 417.Bd -literal 418 while (cnt < 20 && this_variable_name_is_too_long_for_its_own_good && 419 ep != NULL) 420 z = a + really + long + statement + that + needs + 421 two lines + gets + indented + four + spaces + 422 on + the + second + and + subsequent + lines; 423.Ed 424.Pp 425Do not add whitespace at the end of a line, and only use tabs 426followed by spaces 427to form the indentation. 428Do not use more spaces than a tab will produce 429and do not use spaces in front of tabs. 430.Pp 431Closing and opening braces go on the same line as the 432.Ic else . 433Braces that are not necessary may be left out. 434.Bd -literal 435 if (test) 436 stmt; 437 else if (bar) { 438 stmt; 439 stmt; 440 } else 441 stmt; 442.Ed 443.Pp 444No spaces after function names. 445Commas have a space after them. 446No spaces 447after 448.Ql \&( 449or 450.Ql \&[ 451or preceding 452.Ql \&] 453or 454.Ql \&) 455characters. 456.Bd -literal 457 error = function(a1, a2); 458 if (error != 0) 459 exit(error); 460.Ed 461.Pp 462Unary operators do not require spaces, binary operators do. 463Do not use parentheses unless they are required for precedence or unless the 464statement is confusing without them. 465Remember that other people may 466confuse easier than you. 467Do YOU understand the following? 468.Bd -literal 469 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1; 470 k = !(l & FLAGS); 471.Ed 472.Pp 473Exits should be 0 on success, or according to the predefined 474values in 475.Xr sysexits 3 . 476.Bd -literal 477 exit(EX_OK); /* 478 * Avoid obvious comments such as 479 * "Exit 0 on success." 480 */ 481} 482.Ed 483.Pp 484The function type should be on a line by itself 485preceding the function.
| 83.Ed 84.Pp 85Leave another blank line before the header files. 86.Pp 87Kernel include files (i.e.\& 88.Pa sys/*.h ) 89come first; normally, include 90.Aq Pa sys/types.h 91OR 92.Aq Pa sys/param.h , 93but not both. 94.Aq Pa sys/types.h 95includes 96.Aq Pa sys/cdefs.h , 97and it is okay to depend on that. 98.Bd -literal 99#include <sys/types.h> /* Non-local includes in angle brackets. */ 100.Ed 101.Pp 102For a network program, put the network include files next. 103.Bd -literal 104#include <net/if.h> 105#include <net/if_dl.h> 106#include <net/route.h> 107#include <netinet/in.h> 108#include <protocols/rwhod.h> 109.Ed 110.Pp 111Do not use files in 112.Pa /usr/include 113for files in the kernel. 114.Pp 115Leave a blank line before the next group, the 116.Pa /usr 117include files, 118which should be sorted alphabetically by name. 119.Bd -literal 120#include <stdio.h> 121.Ed 122.Pp 123Global pathnames are defined in 124.Aq Pa paths.h . 125Pathnames local 126to the program go in 127.Qq Pa pathnames.h 128in the local directory. 129.Bd -literal 130#include <paths.h> 131.Ed 132.Pp 133Leave another blank line before the user include files. 134.Bd -literal 135#include "pathnames.h" /* Local includes in double quotes. */ 136.Ed 137.Pp 138Do not 139.Ic #define 140or declare names in the implementation namespace except 141for implementing application interfaces. 142.Pp 143The names of 144.Dq unsafe 145macros (ones that have side effects), and the names of macros for 146manifest constants, are all in uppercase. 147The expansions of expression-like macros are either a single token 148or have outer parentheses. 149Put a single tab character between the 150.Ic #define 151and the macro name. 152If a macro is an inline expansion of a function, the function name is 153all in lowercase and the macro has the same name all in uppercase. 154.\" XXX the above conflicts with ANSI style where the names are the 155.\" same and you #undef the macro (if any) to get the function. 156.\" It is not followed for MALLOC(), and not very common if inline 157.\" functions are used. 158If a 159macro needs more than a single line, use braces 160.Ql ( \&{ 161and 162.Ql \&} ) . 163Right-justify the 164backslashes; it makes it easier to read. 165If the macro encapsulates a compound statement, enclose it in a 166.Ic do 167loop, 168so that it can safely be used in 169.Ic if 170statements. 171Any final statement-terminating semicolon should be 172supplied by the macro invocation rather than the macro, to make parsing easier 173for pretty-printers and editors. 174.Bd -literal 175#define MACRO(x, y) do { \e 176 variable = (x) + (y); \e 177 (y) += 2; \e 178} while(0) 179.Ed 180.Pp 181Enumeration values are all uppercase. 182.Bd -literal 183enum enumtype { ONE, TWO } et; 184.Ed 185.Pp 186When declaring variables in structures, declare them sorted by use, then 187by size, and then in alphabetical order. 188The first category normally does not apply, but there are exceptions. 189Each one gets its own line. 190Try to make the structure 191readable by aligning the member names using either one or two tabs 192depending upon your judgment. 193You should use one tab if it suffices to align most of the member names. 194Names following extremely long types 195should be separated by a single space. 196.Pp 197Major structures should be declared at the top of the file in which they 198are used, or in separate header files if they are used in multiple 199source files. 200Use of the structures should be by separate declarations 201and should be 202.Ic extern 203if they are declared in a header file. 204.Bd -literal 205struct foo { 206 struct foo *next; /* List of active foo. */ 207 struct mumble amumble; /* Comment for mumble. */ 208 int bar; /* Try to align the comments. */ 209 struct verylongtypename *baz; /* Won't fit in 2 tabs. */ 210}; 211struct foo *foohead; /* Head of global foo list. */ 212.Ed 213.Pp 214Use 215.Xr queue 3 216macros rather than rolling your own lists, whenever possible. 217Thus, 218the previous example would be better written: 219.Bd -literal 220#include <sys/queue.h> 221 222struct foo { 223 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */ 224 struct mumble amumble; /* Comment for mumble. */ 225 int bar; /* Try to align the comments. */ 226 struct verylongtypename *baz; /* Won't fit in 2 tabs. */ 227}; 228LIST_HEAD(, foo) foohead; /* Head of global foo list. */ 229.Ed 230.Pp 231Avoid using typedefs for structure types. 232This makes it impossible 233for applications to use pointers to such a structure opaquely, which 234is both possible and beneficial when using an ordinary struct tag. 235When convention requires a 236.Ic typedef , 237make its name match the struct tag. 238Avoid typedefs ending in 239.Dq Li _t , 240except as specified in Standard C or by \*[Px]. 241.Bd -literal 242/* Make the structure name match the typedef. */ 243typedef struct bar { 244 int level; 245} BAR; 246typedef int foo; /* This is foo. */ 247typedef const long baz; /* This is baz. */ 248.Ed 249.Pp 250All functions are prototyped somewhere. 251.Pp 252Function prototypes for private functions (i.e. functions not used 253elsewhere) go at the top of the first source module. 254Functions 255local to one source module should be declared 256.Ic static . 257.Pp 258Functions used from other parts of the kernel are prototyped in the 259relevant include file. 260.Pp 261Functions that are used locally in more than one module go into a 262separate header file, e.g.\& 263.Qq Pa extern.h . 264.Pp 265Only use the 266.Dv __P 267macro from the include file 268.Aq Pa sys/cdefs.h 269if the source 270file in general is (to be) compilable with a K&R Old Testament compiler. 271Use of the 272.Dv __P 273macro in new code is discouraged, although modifications 274to existing files should be consistent with that file's conventions. 275.Pp 276In general code can be considered 277.Dq "new code" 278when it makes up about 50% or more of the file(s) involved. 279This is enough 280to break precedents in the existing code and use the current 281.Nm 282guidelines. 283.Pp 284The kernel has a name associated with parameter types, e.g., in the kernel 285use: 286.Bd -literal 287void function(int fd); 288.Ed 289.Pp 290In header files visible to userland applications, prototypes that are 291visible must use either 292.Dq protected 293names (ones beginning with an underscore) 294or no names with the types. 295It is preferable to use protected names. 296E.g., use: 297.Bd -literal 298void function(int); 299.Ed 300.Pp 301or: 302.Bd -literal 303void function(int _fd); 304.Ed 305.Pp 306Prototypes may have an extra space after a tab to enable function names 307to line up: 308.Bd -literal 309static char *function(int _arg, const char *_arg2, struct foo *_arg3, 310 struct bar *_arg4); 311static void usage(void); 312 313/* 314 * All major routines should have a comment briefly describing what 315 * they do. The comment before the "main" routine should describe 316 * what the program does. 317 */ 318int 319main(int argc, char *argv[]) 320{ 321 long num; 322 int ch; 323 char *ep; 324 325.Ed 326.Pp 327For consistency, 328.Xr getopt 3 329should be used to parse options. 330Options 331should be sorted in the 332.Xr getopt 3 333call and the 334.Ic switch 335statement, unless 336parts of the 337.Ic switch 338cascade. 339Elements in a 340.Ic switch 341statement that cascade should have a 342.Li FALLTHROUGH 343comment. 344Numerical arguments should be checked for accuracy. 345Code that cannot be reached should have a 346.Li NOTREACHED 347comment. 348.Bd -literal 349 while ((ch = getopt(argc, argv, "abn:")) != -1) 350 switch (ch) { /* Indent the switch. */ 351 case 'a': /* Don't indent the case. */ 352 aflag = 1; 353 /* FALLTHROUGH */ 354 case 'b': 355 bflag = 1; 356 break; 357 case 'n': 358 num = strtol(optarg, &ep, 10); 359 if (num <= 0 || *ep != '\e0') { 360 warnx("illegal number, -n argument -- %s", 361 optarg); 362 usage(); 363 } 364 break; 365 case '?': 366 default: 367 usage(); 368 /* NOTREACHED */ 369 } 370 argc -= optind; 371 argv += optind; 372.Ed 373.Pp 374Space after keywords 375.Pq Ic if , while , for , return , switch . 376No braces are 377used for control statements with zero or only a single statement unless that 378statement is more than a single line in which case they are permitted. 379Forever loops are done with 380.Ic for Ns 's , 381not 382.Ic while Ns 's . 383.Bd -literal 384 for (p = buf; *p != '\e0'; ++p) 385 ; /* nothing */ 386 for (;;) 387 stmt; 388 for (;;) { 389 z = a + really + long + statement + that + needs + 390 two lines + gets + indented + four + spaces + 391 on + the + second + and + subsequent + lines; 392 } 393 for (;;) { 394 if (cond) 395 stmt; 396 } 397 if (val != NULL) 398 val = realloc(val, newsize); 399.Ed 400.Pp 401Parts of a 402.Ic for 403loop may be left empty. 404Do not put declarations 405inside blocks unless the routine is unusually complicated. 406.Bd -literal 407 for (; cnt < 15; cnt++) { 408 stmt1; 409 stmt2; 410 } 411.Ed 412.Pp 413Indentation is an 8 character tab. 414Second level indents are four spaces. 415If you have to wrap a long statement, put the operator at the end of the 416line. 417.Bd -literal 418 while (cnt < 20 && this_variable_name_is_too_long_for_its_own_good && 419 ep != NULL) 420 z = a + really + long + statement + that + needs + 421 two lines + gets + indented + four + spaces + 422 on + the + second + and + subsequent + lines; 423.Ed 424.Pp 425Do not add whitespace at the end of a line, and only use tabs 426followed by spaces 427to form the indentation. 428Do not use more spaces than a tab will produce 429and do not use spaces in front of tabs. 430.Pp 431Closing and opening braces go on the same line as the 432.Ic else . 433Braces that are not necessary may be left out. 434.Bd -literal 435 if (test) 436 stmt; 437 else if (bar) { 438 stmt; 439 stmt; 440 } else 441 stmt; 442.Ed 443.Pp 444No spaces after function names. 445Commas have a space after them. 446No spaces 447after 448.Ql \&( 449or 450.Ql \&[ 451or preceding 452.Ql \&] 453or 454.Ql \&) 455characters. 456.Bd -literal 457 error = function(a1, a2); 458 if (error != 0) 459 exit(error); 460.Ed 461.Pp 462Unary operators do not require spaces, binary operators do. 463Do not use parentheses unless they are required for precedence or unless the 464statement is confusing without them. 465Remember that other people may 466confuse easier than you. 467Do YOU understand the following? 468.Bd -literal 469 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1; 470 k = !(l & FLAGS); 471.Ed 472.Pp 473Exits should be 0 on success, or according to the predefined 474values in 475.Xr sysexits 3 . 476.Bd -literal 477 exit(EX_OK); /* 478 * Avoid obvious comments such as 479 * "Exit 0 on success." 480 */ 481} 482.Ed 483.Pp 484The function type should be on a line by itself 485preceding the function.
|
| 486The opening brace of the function body should be 487on a line by itself.
|
486.Bd -literal 487static char * 488function(int a1, int a2, float fl, int a4) 489{ 490.Ed 491.Pp 492When declaring variables in functions declare them sorted by size, 493then in alphabetical order; multiple ones per line are okay. 494If a line overflows reuse the type keyword. 495.Pp 496Be careful to not obfuscate the code by initializing variables in 497the declarations. 498Use this feature only thoughtfully. 499DO NOT use function calls in initializers. 500.Bd -literal 501 struct foo one, *two; 502 double three; 503 int *four, five; 504 char *six, seven, eight, nine, ten, eleven, twelve; 505 506 four = myfunction(); 507.Ed 508.Pp 509Do not declare functions inside other functions; ANSI C says that 510such declarations have file scope regardless of the nesting of the 511declaration. 512Hiding file declarations in what appears to be a local 513scope is undesirable and will elicit complaints from a good compiler. 514.Pp 515Casts and 516.Ic sizeof Ns 's 517are not followed by a space. 518Note that 519.Xr indent 1 520does not understand this rule. 521.Pp 522.Dv NULL 523is the preferred null pointer constant. 524Use 525.Dv NULL 526instead of 527.Vt ( "type *" ) Ns 0 528or 529.Vt ( "type *" ) Ns Dv NULL 530in contexts where the compiler knows the 531type, e.g., in assignments. 532Use 533.Vt ( "type *" ) Ns Dv NULL 534in other contexts, 535in particular for all function args. 536(Casting is essential for 537variadic args and is necessary for other args if the function prototype 538might not be in scope.) 539Test pointers against 540.Dv NULL , 541e.g., use: 542.Pp 543.Bd -literal 544(p = f()) == NULL 545.Ed 546.Pp 547not: 548.Bd -literal 549!(p = f()) 550.Ed 551.Pp 552Do not use 553.Ic \&! 554for tests unless it is a boolean, e.g. use 555.Bd -literal 556if (*p == '\e0') 557.Ed 558.Pp 559not 560.Bd -literal 561if (!*p) 562.Ed 563.Pp 564Routines returning 565.Vt "void *" 566should not have their return values cast 567to any pointer type. 568.Pp 569Values in 570.Ic return 571statements should be enclosed in parentheses. 572.Pp 573Use 574.Xr err 3 575or 576.Xr warn 3 , 577do not roll your own. 578.Bd -literal 579 if ((four = malloc(sizeof(struct foo))) == NULL) 580 err(1, (char *)NULL); 581 if ((six = (int *)overflow()) == NULL) 582 errx(1, "number overflowed"); 583 return (eight); 584} 585.Ed 586.Pp 587Old-style function declarations look like this: 588.Bd -literal 589static char * 590function(a1, a2, fl, a4) 591 int a1, a2; /* Declare ints, too, don't default them. */ 592 float fl; /* Beware double vs. float prototype differences. */ 593 int a4; /* List in order declared. */ 594{ 595.Ed 596.Pp 597Use ANSI function declarations unless you explicitly need K&R compatibility. 598Long parameter lists are wrapped with a normal four space indent. 599.Pp 600Variable numbers of arguments should look like this. 601.Bd -literal 602#include <stdarg.h> 603 604void 605vaf(const char *fmt, ...) 606{ 607 va_list ap; 608 609 va_start(ap, fmt); 610 STUFF; 611 va_end(ap); 612 /* No return needed for void functions. */ 613} 614 615static void 616usage() 617{ 618 /* Insert an empty line if the function has no local variables. */ 619.Ed 620.Pp 621Use 622.Xr printf 3 , 623not 624.Xr fputs 3 , 625.Xr puts 3 , 626.Xr putchar 3 , 627whatever; it is faster and usually cleaner, not 628to mention avoiding stupid bugs. 629.Pp 630Usage statements should look like the manual pages 631.Sx SYNOPSIS . 632The usage statement should be structured in the following order: 633.Bl -enum 634.It 635Options without operands come first, 636in alphabetical order, 637inside a single set of brackets 638.Ql ( \&[ 639and 640.Ql \&] ) . 641.It 642Options with operands come next, 643also in alphabetical order, 644with each option and its argument inside its own pair of brackets. 645.It 646Required arguments 647(if any) 648are next, 649listed in the order they should be specified on the command line. 650.It 651Finally, 652any optional arguments should be listed, 653listed in the order they should be specified, 654and all inside brackets. 655.El 656.Pp 657A bar 658.Pq Ql \&| 659separates 660.Dq either-or 661options/arguments, 662and multiple options/arguments which are specified together are 663placed in a single set of brackets. 664.Bd -literal -offset 4n 665"usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en" 666"usage: f [-a | -b] [-c [-dEe] [-n number]]\en" 667.Ed 668.Bd -literal 669 (void)fprintf(stderr, "usage: f [-ab]\en"); 670 exit(EX_USAGE); 671} 672.Ed 673.Pp 674Note that the manual page options description should list the options in 675pure alphabetical order. 676That is, without regard to whether an option takes arguments or not. 677The alphabetical ordering should take into account the case ordering 678shown above. 679.Pp 680New core kernel code should be reasonably compliant with the 681.Nm 682guides. 683The guidelines for third-party maintained modules and device drivers are more 684relaxed but at a minimum should be internally consistent with their style. 685.Pp 686Stylistic changes (including whitespace changes) are hard on the source 687repository and are to be avoided without good reason. 688Code that is approximately 689.Fx 690KNF 691.Nm 692compliant in the repository must not diverge from compliance. 693.Pp 694Whenever possible, code should be run through a code checker 695(e.g., 696.Xr lint 1 697or 698.Nm gcc Fl Wall ) 699and produce minimal warnings. 700.Sh SEE ALSO 701.Xr indent 1 , 702.Xr lint 1 , 703.Xr err 3 , 704.Xr sysexits 3 , 705.Xr warn 3 706.Sh HISTORY 707This man page is largely based on the 708.Pa src/admin/style/style 709file from the 710.Bx 4.4 Lite2 711release, with occasional updates to reflect the current practice and 712desire of the 713.Fx 714project.
| 488.Bd -literal 489static char * 490function(int a1, int a2, float fl, int a4) 491{ 492.Ed 493.Pp 494When declaring variables in functions declare them sorted by size, 495then in alphabetical order; multiple ones per line are okay. 496If a line overflows reuse the type keyword. 497.Pp 498Be careful to not obfuscate the code by initializing variables in 499the declarations. 500Use this feature only thoughtfully. 501DO NOT use function calls in initializers. 502.Bd -literal 503 struct foo one, *two; 504 double three; 505 int *four, five; 506 char *six, seven, eight, nine, ten, eleven, twelve; 507 508 four = myfunction(); 509.Ed 510.Pp 511Do not declare functions inside other functions; ANSI C says that 512such declarations have file scope regardless of the nesting of the 513declaration. 514Hiding file declarations in what appears to be a local 515scope is undesirable and will elicit complaints from a good compiler. 516.Pp 517Casts and 518.Ic sizeof Ns 's 519are not followed by a space. 520Note that 521.Xr indent 1 522does not understand this rule. 523.Pp 524.Dv NULL 525is the preferred null pointer constant. 526Use 527.Dv NULL 528instead of 529.Vt ( "type *" ) Ns 0 530or 531.Vt ( "type *" ) Ns Dv NULL 532in contexts where the compiler knows the 533type, e.g., in assignments. 534Use 535.Vt ( "type *" ) Ns Dv NULL 536in other contexts, 537in particular for all function args. 538(Casting is essential for 539variadic args and is necessary for other args if the function prototype 540might not be in scope.) 541Test pointers against 542.Dv NULL , 543e.g., use: 544.Pp 545.Bd -literal 546(p = f()) == NULL 547.Ed 548.Pp 549not: 550.Bd -literal 551!(p = f()) 552.Ed 553.Pp 554Do not use 555.Ic \&! 556for tests unless it is a boolean, e.g. use 557.Bd -literal 558if (*p == '\e0') 559.Ed 560.Pp 561not 562.Bd -literal 563if (!*p) 564.Ed 565.Pp 566Routines returning 567.Vt "void *" 568should not have their return values cast 569to any pointer type. 570.Pp 571Values in 572.Ic return 573statements should be enclosed in parentheses. 574.Pp 575Use 576.Xr err 3 577or 578.Xr warn 3 , 579do not roll your own. 580.Bd -literal 581 if ((four = malloc(sizeof(struct foo))) == NULL) 582 err(1, (char *)NULL); 583 if ((six = (int *)overflow()) == NULL) 584 errx(1, "number overflowed"); 585 return (eight); 586} 587.Ed 588.Pp 589Old-style function declarations look like this: 590.Bd -literal 591static char * 592function(a1, a2, fl, a4) 593 int a1, a2; /* Declare ints, too, don't default them. */ 594 float fl; /* Beware double vs. float prototype differences. */ 595 int a4; /* List in order declared. */ 596{ 597.Ed 598.Pp 599Use ANSI function declarations unless you explicitly need K&R compatibility. 600Long parameter lists are wrapped with a normal four space indent. 601.Pp 602Variable numbers of arguments should look like this. 603.Bd -literal 604#include <stdarg.h> 605 606void 607vaf(const char *fmt, ...) 608{ 609 va_list ap; 610 611 va_start(ap, fmt); 612 STUFF; 613 va_end(ap); 614 /* No return needed for void functions. */ 615} 616 617static void 618usage() 619{ 620 /* Insert an empty line if the function has no local variables. */ 621.Ed 622.Pp 623Use 624.Xr printf 3 , 625not 626.Xr fputs 3 , 627.Xr puts 3 , 628.Xr putchar 3 , 629whatever; it is faster and usually cleaner, not 630to mention avoiding stupid bugs. 631.Pp 632Usage statements should look like the manual pages 633.Sx SYNOPSIS . 634The usage statement should be structured in the following order: 635.Bl -enum 636.It 637Options without operands come first, 638in alphabetical order, 639inside a single set of brackets 640.Ql ( \&[ 641and 642.Ql \&] ) . 643.It 644Options with operands come next, 645also in alphabetical order, 646with each option and its argument inside its own pair of brackets. 647.It 648Required arguments 649(if any) 650are next, 651listed in the order they should be specified on the command line. 652.It 653Finally, 654any optional arguments should be listed, 655listed in the order they should be specified, 656and all inside brackets. 657.El 658.Pp 659A bar 660.Pq Ql \&| 661separates 662.Dq either-or 663options/arguments, 664and multiple options/arguments which are specified together are 665placed in a single set of brackets. 666.Bd -literal -offset 4n 667"usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en" 668"usage: f [-a | -b] [-c [-dEe] [-n number]]\en" 669.Ed 670.Bd -literal 671 (void)fprintf(stderr, "usage: f [-ab]\en"); 672 exit(EX_USAGE); 673} 674.Ed 675.Pp 676Note that the manual page options description should list the options in 677pure alphabetical order. 678That is, without regard to whether an option takes arguments or not. 679The alphabetical ordering should take into account the case ordering 680shown above. 681.Pp 682New core kernel code should be reasonably compliant with the 683.Nm 684guides. 685The guidelines for third-party maintained modules and device drivers are more 686relaxed but at a minimum should be internally consistent with their style. 687.Pp 688Stylistic changes (including whitespace changes) are hard on the source 689repository and are to be avoided without good reason. 690Code that is approximately 691.Fx 692KNF 693.Nm 694compliant in the repository must not diverge from compliance. 695.Pp 696Whenever possible, code should be run through a code checker 697(e.g., 698.Xr lint 1 699or 700.Nm gcc Fl Wall ) 701and produce minimal warnings. 702.Sh SEE ALSO 703.Xr indent 1 , 704.Xr lint 1 , 705.Xr err 3 , 706.Xr sysexits 3 , 707.Xr warn 3 708.Sh HISTORY 709This man page is largely based on the 710.Pa src/admin/style/style 711file from the 712.Bx 4.4 Lite2 713release, with occasional updates to reflect the current practice and 714desire of the 715.Fx 716project.
|