Coding Style in Linux kernel          Peter Chang          2012/06/17
Reference“Linux Kernel Coding Style”, Linus Torvals, https://computing.llnl.gov/linux/slurm/coding_style.pdf“Documentation...
“First off, Id suggest printing out a copy ofthe GNU coding standards, and NOT read it.Burn them, its a great symbolic ges...
Indentation
IndentationAll tabs are 8 characters.Use tabs.If your code need 3 layers of indentation, it’syour problem. Solve it!
IndentationDon’t put two statement in the same line.Use a good editor. Don’t put andy empty linein the end of any file.
IndentationPut switch and case into the same layerof indentation
Indentation
IndentationGood examples:  fs/*  kernel/*Bad examples:  drivers/scsi/sg.c
Break long lines & strings
Break long lines & strings There are only   80 char. in a line. Because we hate this:
Break long lines & strings
Braces
Braces
Braces
Braces
Braces
Braces
Braces
Braces
BracesGood examples:  drivers/scsi/qla1280.c  kernel/*.cBad examples:  fs/devfs/*
Spaces
Spaces“To be, or not to be”
SpacesUse a space after these keywords:  if, switch, case, for, do, whileDo not add spaces after these keywords:  sizeof, ...
SpacesGood example:  s = sizeof(struct file);Suck example:  s=sizeof( struct file );
SpacesAdd a space before and after the followingbinary and ternary operators:  =,+,-,*,/  <,>,%,&,|,^  <= , >= , == , != ,...
SpacesDO NOT       Add a space after the followingoperators:  &, *, +, -, ~, !, sizeof, typeof, alignof,  __attribute__, d...
SpacesDO NOT      add a space before and after thefollowing operators:  ++,--
SpacesDO NOT      add a space before and after thefollowing operators:  .  ->
Naming
NamingBe descriptiveBe conciseGood example:  void enable_mem_mailbox();
NamingNo MiXedCaSeBad examples:  int CommandAllocationGroupSize;  void  DAC960_V1_EnableMemoryMailboxInterfa  ce();
NamingGlobal variable should be use only ifthey are absolutely necessary.
NamingLocal variable should be short and the pointGood example:  i,j ( as a counter for a loop )Bad example:  loop_counter
NamingDon’t encoding the type of a function intothe name (a.k.a. Hungarian notation).“It’s brain damaged” ~ Linus Torvalds
Functions
FunctionsDo one thing, and do it wellShort, one or two screens of text
FunctionsOkay to have longer function doing smalldifferent things
Functions“如果你寫出了⼀一個很複雜的function,表示你可能程度比高中⼀一年級的學生還差,因為你不會用function”~ Linus Torvalds
FunctionsIf more than 10 local variables, it’s toocomplex
Functions“人最多同時只能記7件不同的事情。如果你覺得你是天才,那或許你兩個星期後就還看的懂你那複雜的函式”~ Linus Torvalds
FunctionsSeparate different functions with a blank lineIf your function will be exported, useEXPORT* macro
Functions
IndentationGood examples:  fs/*.cBad examples:  drivers/hotplug/ibmphp_res.c     include WTF 370 lines  drivers/usb/serial...
GOTOCentralize exiting of functions
被封印的GOTO“危險,不要用” ~ 好像小時候聽大人講過“下⼀一節是要講Goto,但我們跳過,你們寫程式也不要用Goto” ~ 好像當初上大⼀一程設上課有講過
只是歷史遺跡?組合語言發展過來的遺跡? jump? branch?
難道GOTO錯了嗎?
As the matter of fact, ...  The equivalent to GOTO statement is used  frequently by compiler.  For what?    Unconditional ...
Timing of using GOTOLet function from multiple exit to only oneexit
Reason of using GOTOUnconditional statements are easier tounderstand and follownested is reduced!!!errors by not updating ...
Example of using GOTO
Comment
CommentsBad comments  explain how code works  say who wrote this function  have last modified date  have other trivial things
CommentsGood comments  explain what  explain why  should be at the beginning of function
CommentsDo not use:  / statement of comment ( C99-style )   /Do use:  /* statement of comment ( C89-style) */
Comments
Comments
Comments
Kconfig
Indentation of KconfigLines under a "config" definition are indentedwith one tabhelp text is indented an additional twospaces
Indentation of Kconfig
Unstable Features in Kconfig  Features that might still be considered  unstable should be defined as dependent on  "EXPERIME...
Unstable Features in Kconfig
Dangerous feature in Kconfig seriously dangerous features should advertise this prominently in their prompt string
Dangerous feature in Kconfig
Macro, enum, RTL
CAPITALIZENames of macros defining constantslabels in enums  For defining several related constants
CAPITALIZEExample:  #define CONSTANT 0xffff0000
LOOOOONG MacroMacros with multiple statements should beenclosed in a do - while block
LOOOOONG Macro
Don’t use macro in these cases 1. macros that affect control flow   It looks like a function call but exits the   "calling"...
Don’t use macro in these cases
Don’t use macro in these cases 2. macros that depend on having a local variable with a magic name   might look like a good...
Don’t use macro in these cases Example for 2:   #define FOO(val) bar(index, val)
Don’t use macro in these cases 3. macros with arguments that are used as l-values   Ex: FOO(x) = y;   will bite you if som...
Don’t use macro in these cases 4. forgetting about precedence   macros defining constants using   expressions must enclose ...
Don’t use macro in these cases
Allocate memory
Function return value and names
Unwritten rules
Unwritten rulesUse code that is already present  string  byte order functions  linked lists
typedef is evil
EVIL! EVIL! EVIL!It hides the real type of the variableAllows programmers to get into trouble   large struct. on the stack...
Well, mostly...Base system types  list_t  u8, u16, u64Function pointer
No #ifdef in .c files#ifdef belongs in .h fileLet your compiler do its work
Labeled elements in    Initializers
Labeled elements in    Initializers
Labeled elements in    Initializers
Labeled elements in    Initializers
Labeled elements in    Initializers
Coding style of Linux Kernel
Upcoming SlideShare
Loading in …5
×

Coding style of Linux Kernel

3,978 views

Published on

Published in: Technology, News & Politics
0 Comments
12 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,978
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
107
Comments
0
Likes
12
Embeds 0
No embeds

No notes for slide

Coding style of Linux Kernel

  1. 1. Coding Style in Linux kernel Peter Chang 2012/06/17
  2. 2. Reference“Linux Kernel Coding Style”, Linus Torvals, https://computing.llnl.gov/linux/slurm/coding_style.pdf“Documentation / Coding-Style”, Greg Kroah-Hartman, IBM, Linux Symposium 2002 (Slide version: http://www.kroah.com/linux/ talks/ols_2002_kernel_codingstyle_talk/html/ index.html)http://www.kernel.org/doc/Documentation/CodingStyle
  3. 3. “First off, Id suggest printing out a copy ofthe GNU coding standards, and NOT read it.Burn them, its a great symbolic gesture.”~ Linus Torvalds
  4. 4. Indentation
  5. 5. IndentationAll tabs are 8 characters.Use tabs.If your code need 3 layers of indentation, it’syour problem. Solve it!
  6. 6. IndentationDon’t put two statement in the same line.Use a good editor. Don’t put andy empty linein the end of any file.
  7. 7. IndentationPut switch and case into the same layerof indentation
  8. 8. Indentation
  9. 9. IndentationGood examples: fs/* kernel/*Bad examples: drivers/scsi/sg.c
  10. 10. Break long lines & strings
  11. 11. Break long lines & strings There are only 80 char. in a line. Because we hate this:
  12. 12. Break long lines & strings
  13. 13. Braces
  14. 14. Braces
  15. 15. Braces
  16. 16. Braces
  17. 17. Braces
  18. 18. Braces
  19. 19. Braces
  20. 20. Braces
  21. 21. BracesGood examples: drivers/scsi/qla1280.c kernel/*.cBad examples: fs/devfs/*
  22. 22. Spaces
  23. 23. Spaces“To be, or not to be”
  24. 24. SpacesUse a space after these keywords: if, switch, case, for, do, whileDo not add spaces after these keywords: sizeof, typeof, alignof, __attribute__
  25. 25. SpacesGood example: s = sizeof(struct file);Suck example: s=sizeof( struct file );
  26. 26. SpacesAdd a space before and after the followingbinary and ternary operators: =,+,-,*,/ <,>,%,&,|,^ <= , >= , == , != , ? , :
  27. 27. SpacesDO NOT Add a space after the followingoperators: &, *, +, -, ~, !, sizeof, typeof, alignof, __attribute__, define
  28. 28. SpacesDO NOT add a space before and after thefollowing operators: ++,--
  29. 29. SpacesDO NOT add a space before and after thefollowing operators: . ->
  30. 30. Naming
  31. 31. NamingBe descriptiveBe conciseGood example: void enable_mem_mailbox();
  32. 32. NamingNo MiXedCaSeBad examples: int CommandAllocationGroupSize; void DAC960_V1_EnableMemoryMailboxInterfa ce();
  33. 33. NamingGlobal variable should be use only ifthey are absolutely necessary.
  34. 34. NamingLocal variable should be short and the pointGood example: i,j ( as a counter for a loop )Bad example: loop_counter
  35. 35. NamingDon’t encoding the type of a function intothe name (a.k.a. Hungarian notation).“It’s brain damaged” ~ Linus Torvalds
  36. 36. Functions
  37. 37. FunctionsDo one thing, and do it wellShort, one or two screens of text
  38. 38. FunctionsOkay to have longer function doing smalldifferent things
  39. 39. Functions“如果你寫出了⼀一個很複雜的function,表示你可能程度比高中⼀一年級的學生還差,因為你不會用function”~ Linus Torvalds
  40. 40. FunctionsIf more than 10 local variables, it’s toocomplex
  41. 41. Functions“人最多同時只能記7件不同的事情。如果你覺得你是天才,那或許你兩個星期後就還看的懂你那複雜的函式”~ Linus Torvalds
  42. 42. FunctionsSeparate different functions with a blank lineIf your function will be exported, useEXPORT* macro
  43. 43. Functions
  44. 44. IndentationGood examples: fs/*.cBad examples: drivers/hotplug/ibmphp_res.c include WTF 370 lines drivers/usb/serial/usbserials.c use WTF 21 local variables
  45. 45. GOTOCentralize exiting of functions
  46. 46. 被封印的GOTO“危險,不要用” ~ 好像小時候聽大人講過“下⼀一節是要講Goto,但我們跳過,你們寫程式也不要用Goto” ~ 好像當初上大⼀一程設上課有講過
  47. 47. 只是歷史遺跡?組合語言發展過來的遺跡? jump? branch?
  48. 48. 難道GOTO錯了嗎?
  49. 49. As the matter of fact, ... The equivalent to GOTO statement is used frequently by compiler. For what? Unconditional jump instruction
  50. 50. Timing of using GOTOLet function from multiple exit to only oneexit
  51. 51. Reason of using GOTOUnconditional statements are easier tounderstand and follownested is reduced!!!errors by not updating individual exit pointswhen making modifications are preventedsaves the compiler work to optimizeredundant code away ;)
  52. 52. Example of using GOTO
  53. 53. Comment
  54. 54. CommentsBad comments explain how code works say who wrote this function have last modified date have other trivial things
  55. 55. CommentsGood comments explain what explain why should be at the beginning of function
  56. 56. CommentsDo not use: / statement of comment ( C99-style ) /Do use: /* statement of comment ( C89-style) */
  57. 57. Comments
  58. 58. Comments
  59. 59. Comments
  60. 60. Kconfig
  61. 61. Indentation of KconfigLines under a "config" definition are indentedwith one tabhelp text is indented an additional twospaces
  62. 62. Indentation of Kconfig
  63. 63. Unstable Features in Kconfig Features that might still be considered unstable should be defined as dependent on "EXPERIMENTAL "
  64. 64. Unstable Features in Kconfig
  65. 65. Dangerous feature in Kconfig seriously dangerous features should advertise this prominently in their prompt string
  66. 66. Dangerous feature in Kconfig
  67. 67. Macro, enum, RTL
  68. 68. CAPITALIZENames of macros defining constantslabels in enums For defining several related constants
  69. 69. CAPITALIZEExample: #define CONSTANT 0xffff0000
  70. 70. LOOOOONG MacroMacros with multiple statements should beenclosed in a do - while block
  71. 71. LOOOOONG Macro
  72. 72. Don’t use macro in these cases 1. macros that affect control flow It looks like a function call but exits the "calling" function; dont break the internal parsers of those who will read the code.
  73. 73. Don’t use macro in these cases
  74. 74. Don’t use macro in these cases 2. macros that depend on having a local variable with a magic name might look like a good thing, but its confusing as hell when one reads the code and its prone to breakage from seemingly innocent changes.
  75. 75. Don’t use macro in these cases Example for 2: #define FOO(val) bar(index, val)
  76. 76. Don’t use macro in these cases 3. macros with arguments that are used as l-values Ex: FOO(x) = y; will bite you if somebody e.g. turns FOO into an inline function
  77. 77. Don’t use macro in these cases 4. forgetting about precedence macros defining constants using expressions must enclose the expression in parentheses. Beware of similar issues with macros using parameters.
  78. 78. Don’t use macro in these cases
  79. 79. Allocate memory
  80. 80. Function return value and names
  81. 81. Unwritten rules
  82. 82. Unwritten rulesUse code that is already present string byte order functions linked lists
  83. 83. typedef is evil
  84. 84. EVIL! EVIL! EVIL!It hides the real type of the variableAllows programmers to get into trouble large struct. on the stack large struct. passed as return valueCan hid e long structure definition pick a better nametypedef just signify a pointer type could you be lazier?
  85. 85. Well, mostly...Base system types list_t u8, u16, u64Function pointer
  86. 86. No #ifdef in .c files#ifdef belongs in .h fileLet your compiler do its work
  87. 87. Labeled elements in Initializers
  88. 88. Labeled elements in Initializers
  89. 89. Labeled elements in Initializers
  90. 90. Labeled elements in Initializers
  91. 91. Labeled elements in Initializers

×