linux内核编程风格.pdf
《linux内核编程风格.pdf》由会员分享,可在线阅读,更多相关《linux内核编程风格.pdf(20页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、 Linux kernel coding styleThis is a short document describing the preferred coding style for thelinux kernel.Coding style is very personal,and I wont _force_ myviews on anybody,but this is what goes for anything that I have to beable to maintain,and Id prefer it for most other things too.Pleaseat le
2、ast consider the points made here.First off,Id suggest printing out a copy of the GNU coding standards,and NOT read it.Burn them,its a great symbolic gesture.Anyway,here goes:Chapter 1:IndentationTabs are 8 characters,and thus indentations are also 8 characters.There are heretic movements that try t
3、o make indentations 4(or even 2!)characters deep,and that is akin to trying to define the value of PI tobe 3.Rationale:The whole idea behind indentation is to clearly define wherea block of control starts and ends.Especially when youve been lookingat your screen for 20 straight hours,youll find it a
4、 lot easier to seehow the indentation works if you have large indentations.Now,some people will claim that having 8-character indentations makesthe code move too far to the right,and makes it hard to read on a80-character terminal screen.The answer to that is that if you needmore than 3 levels of in
5、dentation,youre screwed anyway,and should fixyour program.In short,8-char indents make things easier to read,and have the addedbenefit of warning you when youre nesting your functions too deep.Heed that warning.The preferred way to ease multiple indentation levels in a switch statement isto align th
6、e switch and its subordinate case labels in the same columninstead of double-indenting the case labels.E.g.:switch(suffix)case G:case g:mem=30;break;case M:case m:mem=20;break;case K:case k:mem y).else.Rationale:K&R.Also,note that this brace-placement also minimizes the number of empty(or almost emp
7、ty)lines,without any loss of readability.Thus,as thesupply of new-lines on your screen is not a renewable resource(think25-line terminal screens here),you have more empty lines to putcomments on.Do not unnecessarily use braces where a single statement will do.if(condition)action();andif(condition)do
8、_this();elsedo_that();This does not apply if only one branch of a conditional statement is a singlestatement;in the latter case use braces in both branches:if(condition)do_this();do_that();else otherwise();3.1:SpacesLinux kernel style for use of spaces depends(mostly)onfunction-versus-keyword usage.
9、Use a space after(most)keywords.Thenotable exceptions are sizeof,typeof,alignof,and _attribute_,which looksomewhat like functions(and are usually used with parentheses in Linux,although they are not required in the language,as in:sizeof info afterstruct fileinfo info;is declared).So use a space afte
10、r these keywords:if,switch,case,for,do,whilebut not with sizeof,typeof,alignof,or _attribute_.E.g.,s=sizeof(struct file);Do not add spaces around(inside)parenthesized expressions.This example is*bad*:s=sizeof(struct file);When declaring pointer data or a function that returns a pointer type,theprefe
11、rred use of*is adjacent to the data name or function name and notadjacent to the type name.Examples:char*linux_banner;unsigned long long memparse(char*ptr,char*retptr);char*match_strdup(substring_t*s);Use one space around(on each side of)most binary and ternary operators,such as any of these:=+-*/%|
12、&=!=?:but no space after unary operators:&*+-!sizeof typeof alignof _attribute_ definedno space before the postfix increment&decrement unary operators:+-no space after the prefix increment&decrement unary operators:+-and no space around the.and-structure member operators.Do not leave trailing whites
13、pace at the ends of lines.Some editors withsmart indentation will insert whitespace at the beginning of new lines asappropriate,so you can start typing the next line of code right away.However,some such editors do not remove the whitespace if you end up notputting a line of code there,such as if you
14、 leave a blank line.As a result,you end up with lines containing trailing whitespace.Git will warn you about patches that introduce trailing whitespace,and canoptionally strip the trailing whitespace for you;however,if applying a seriesof patches,this may make later patches in the series fail by cha
15、nging theircontext lines.Chapter 4:NamingC is a Spartan language,and so should your naming be.Unlike Modula-2and Pascal programmers,C programmers do not use cute names likeThisVariableIsATemporaryCounter.A C programmer would call thatvariable tmp,which is much easier to write,and not the least mored
16、ifficult to understand.HOWEVER,while mixed-case names are frowned upon,descriptive names forglobal variables are a must.To call a global function foo is ashooting offense.GLOBAL variables(to be used only if you _really_ need them)need tohave descriptive names,as do global functions.If you have a fun
17、ctionthat counts the number of active users,you should call thatcount_active_users()or similar,you should _not_ call it cntusr().Encoding the type of a function into the name(so-called Hungariannotation)is brain damaged-the compiler knows the types anyway and cancheck those,and it only confuses the
18、programmer.No wonder MicroSoftmakes buggy programs.LOCAL variable names should be short,and to the point.If you havesome random integer loop counter,it should probably be called i.Calling it loop_counter is non-productive,if there is no chance of itbeing mis-understood.Similarly,tmp can be just abou
19、t any type ofvariable that is used to hold a temporary value.If you are afraid to mix up your local variable names,you have anotherproblem,which is called the function-growth-hormone-imbalance syndrome.See chapter 6(Functions).Chapter 5:TypedefsPlease dont use things like vps_t.Its a _mistake_ to us
20、e typedef for structures and pointers.When you see avps_t a;in the source,what does it mean?In contrast,if it saysstruct virtual_container*a;you can actually tell what a is.Lots of people think that typedefs help readability.Not so.They areuseful only for:(a)totally opaque objects(where the typedef
21、is actively used to _hide_ what the object is).Example:pte_t etc.opaque objects that you can only access using the proper accessor functions.NOTE!Opaqueness and accessor functions are not good in themselves.The reason we have them for things like pte_t etc.is that there really is absolutely _zero_ p
22、ortably accessible information there.(b)Clear integer types,where the abstraction _helps_ avoid confusion whether it is int or long.u8/u16/u32 are perfectly fine typedefs,although they fit into category(d)better than here.NOTE!Again-there needs to be a _reason_ for this.If something is unsigned long
23、,then theres no reason to dotypedef unsigned long myflags_t;but if there is a clear reason for why it under certain circumstances might be an unsigned int and under other configurations might be unsigned long,then by all means go ahead and use a typedef.(c)when you use sparse to literally create a _
24、new_ type for type-checking.(d)New types which are identical to standard C99 types,in certain exceptional circumstances.Although it would only take a short amount of time for the eyes and brain to become accustomed to the standard types like uint32_t,some people object to their use anyway.Therefore,
25、the Linux-specific u8/u16/u32/u64 types and their signed equivalents which are identical to standard types are permitted-although they are not mandatory in new code of your own.When editing existing code which already uses one or the other set of types,you should conform to the existing choices in t
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- linux 内核 编程 风格
限制150内