Summarize the Linux kernel development coding style, easy to write code later reference.
Here are just a list of some rules, specific instructions can be consulted: kernel source (Documentation/codingstyle)
01-Indent
Indent tab, and tab width is 8 characters
Swich and case alignment without indentation
switch (suffix) {
Case ' G ':
Case ' G ':
Mem <<= 30;
Break
Case ' M ':
Case ' m ':
Mem <<= 20;
Break
Case ' K ':
Case ' K ':
Mem <<= 10;
/* Fall through */
Default
Break
}
There is only one expression on a line
if (condition) do_this; /* Bad Example */
Do not indent with a space (except for comments or documents)
02-line length of code is controlled within 80 characters
Keep legibility when long lines are truncated
void Fun (int A, int b, int c)
{
if (condition)
PRINTK (kern_warning "WARNING" a long printk with "
"3 Parameters A:%u B:%u"
"C:%u \ n", A, B, c);
else next_statement;
}
03-position of parentheses and spaces
The curly brace of the function is another line
int function (int x)
{/* This curly brace {another line * * * body of function
}
Non-function statement block (if, switch, for, while, do) without another line
if (x is True) {/* This curly brace {does not have another row */We do Y
}
Only one line of statement blocks without curly braces
if (condition)
Action ();
If the if uses curly braces, then else use curly braces even if there is only one line
if (condition) {
Do_this ();
Do_that ();
} else {
otherwise ();
}
Append a space after the following keywords
If, switch, case, for, does, while
After the following keywords * do not * append a space
sizeof, typeof, Alignof, __attribute
s = sizeof (struct file); /* Good */s = sizeof (struct file); /* Bad */
When you define a pointer, * close to the function name or variable name
Char *linux_banner;
unsigned long long memparse (char *ptr, char **retptr);
Char *match_strdup (substring_t *s);
The following two and ternary operators left a space around
= +-< > */% | & ^ <= >= = = =? :
Next to the unary operator * Do not * leave blank spaces
& * +-~! sizeof typeof alignof __attribute__ defined
Do not leave spaces in front of the suffix operator (+ +-)
Do not leave spaces behind the prefix operator (+ +-)
Do not leave spaces before or after the struct member operator (.)
Do not have extra spaces after each line of code
04-Naming
A global variable or function (used when it is really necessary) to have a descriptive name
Count_active_users ()/* Good */CNTUSR ()/* CNT */
The local variable name should be concise (this rule is more abstract, only to look at the other people in the kernel code naming method)
05–typedefs
Try not to use TypeDef, using typedef primarily for the following purposes:
1. Completely opaque types (access to these types also require corresponding access functions)
Ex. pid_t, uid_t, pte_t ... Wait a minute
2. Avoid the problem of integral type data
such as int, long length is inconsistent in different architectures, etc., use u8/u16/u32 instead of integer definition
3. When using Kernel's sparse tool for variable type checking, a typedef can be a type.
4. Defining new types in the C99 standard
5. For type safety of user space
A typedef is used when the structure of the kernel space is mapped to user space, so that user space can function even if the data structure of the kernel space changes
06-function
function to be brief, a function to do only one thing
function length generally not more than 2 screen (1 screen size is 80x24), that is, 48 lines
If the switch in the function has a lot of simple case statements, then the 2 screen can be
Local variables in a function cannot exceed 5~10
There is an empty line between the function and the function, but there is no space between the export*
int One_func (void)
{
return 0;
}
int system_is_up (void)
{
return system_state = = system_running;
}
Export_symbol (SYSTEM_IS_UP);
07-Function Exit
The exit of the function is set together, especially when the memory needs to be cleaned up. (Goto is not a scourge, and sometimes useful.)
int fun (int a)
{
int result = 0;
Char *buffer = Kmalloc (SIZE);
if (buffer = = NULL)
Return-enomem;
if (condition1) {
while (LOOP1) {
...
}
result = 1;
Goto out;
}
...
Out
Kfree (buffer);
return result;
}
08-Comments
Comment on what code did, not how to do it
Use C89 's annotation style (/* ... */), do not use the C99 annotation style (//...)
annotation defines the data, whether it is a base type or a derived type
09-Method of controlling indentation
Use Emacs to ensure indentation, and the configuration in. Emacs is as follows:
(Defun c-lineup-arglist-tabs-only (ignored)
"Line up argument lists by tabs, not Spaces" (Let* (anchor (C-langelem-pos c-syntactic-element)
(Column (C-langelem-2nd-pos c-syntactic-element))
(Offset (-(1+ column) anchor))
(Steps (floor offset c-basic-offset)))
(* (max steps 1)
C-basic-offset)))
(Add-hook ' C-mode-common-hook
(Lambda ()
;; ADD kernel Style
(C-add-style
"Linux-tabs-only"
' ("Linux" (c-offsets-alist
(Arglist-cont-nonempty
C-lineup-gcc-asm-reg
c-lineup-arglist-tabs-only)))))
(Add-hook ' C-mode-hook
(Lambda ()
(Let ((filename (buffer-file-name)))
;; Enable kernel mode for the appropriate files
(When (and filename
(String-match (expand-file-name "~/src/linux-trees")
FileName))
(setq Indent-tabs-mode T)
(C-set-style "Linux-tabs-only"))))
Use the indent script to guarantee indentation. (Script location: scripts/lindent)
10-kconfig configuration file
"Config" the next line to indent a tab, "Help" is indented 2 spaces
Config AUDIT
BOOL "Auditing support" depends on NET
Help
Enable auditing infrastructure that can is used with another
Kernel subsystem, such as SELinux (which requires this for logging of AVC messages output). Does not do System-call
Auditing without Config_auditsyscall.
Unstable features to add *experimental*
Config Slub
Depends on experimental &&! Arch_uses_slab_page_struct
BOOL "Slub (unqueued Allocator)" ...
Dangerous features to add *dangerous*.
Config ADFS_FS_RW
BOOL "ADFS write Support (dangerous)" depends on Adfs_fs
...
A description of the kconfig can be found in: documentation/kbuild/kconfig-language.txt
11-Data structure
Struct to include a reference count field (no automatic garbage collection in the kernel, manual free memory required)
Lock is required to ensure structural data consistency
Sometimes multiple layers of reference counting are required in structs
Ex. Struc mm_struct, struct super_block
12-macro, enum type, and RTL
Macro defines constants the latter label uses uppercase letters
#define CONSTANT 0x12345
When a macro defines a multiline statement to be placed in the Do-while, the name of the macro is lowercase
#define MACROFUN (A, B, c) \
do {\
if (a = = 5) \
Do_this (b, c); \
} while (0)
When a macro defines an expression to be placed in ()
#define CONSTANT 0x4000
#define CONSTEXP (CONSTANT | 3)
Enumeration types are used to define multiple linked constants
13-Print Kernel messages
Keep your printing information concise and clear
For example, instead of "dont", use "do not" or "Don t"
Kernel information does not need to end with "."
Printing "(%d)" does not make any sense and should be avoided
Select the appropriate print level (debug, warning, error, etc.)
14-Allocating memory
sizeof (pointer) instead of sizeof (struct) when allocating memory
p = kmalloc (sizeof (*P), ...);
In this case, when p points to other structures, the code above is still available
The return value to void pointer after allocating memory is superfluous, and the C language itself will complete this step
15-The drawbacks of the inline
If a function has more than 3 rows, do not use inline to mark it
16-function return value and name
If the function function is an action or a command, the error-code of the int type is returned.
For example, the Add_work () function returns 0 on successful execution and returns the corresponding Error-code (ex.-ebusy) on failure.
If function function is a judgment, return "0" indicates failure, "1" indicates success
All exported functions, common functions require the above 2 requirements
All private (static) functions, not mandatory, but best to meet the above 2 requirements
If the function returns a true calculation instead of a success, the failure is expressed by returning a value outside the range of the computed result
A function that returns a pointer, for example, by returning NULL to indicate a failure
17-Do not re-invent kernel macros
Kernel-defined macros in the header file Include/linux/kernel.h, when you want to define a new macro, first see if there is a similar macro available
18-editor Mode Lines and other
Do not include the content of a particular editor or the configuration of other tools in your code.
For example, emacs configuration
-*-Mode:c-*-or
/*local Variables:
Compile-command: "Gcc-dmagic_debug_flag foo.c"
End:
*/
Configuration of Vim
/* Vim:set sw=8 Noet */
The development tools that everyone uses may not be the same, and such a configuration is rubbish for some people
Introduction to Kernel code formatting tools
checkpatch.pl-Check whether the source or patch conforms to the specification
Lindent-Indentation of formatted code
These 2 tools are in the Scripts folder in the kernel code tree.
Coding style--linux kernel developed coding style