Linux 内核编码风格【转】

原文:http://www.cnblogs.com/baochuan/archive/2013/04/08/3006615.html
Linux 内核编码风格
像其他大型软件一样,Linux制订了一套编码风格,对代码的格式、风格和布局做出了规定。我写这篇的目的也就是希望大家能够从中借鉴,有利于大家提高编程效率。
像Linux内核这样大型软件中,涉及许许多多的开发者,故它的编码风格也很有参考价值。
括号 
1、左括号紧跟在语句的最后,与语句在相同的一行。而右括号要另起一行,作为该行的第一个字符。
2、如果接下来的部分是相同语句的一部分,那么右括号就不单独占一行。
3、还有
4、函数采用以下的书写方式:
5、最后不需要一定使用括号的语句可以忽略它:
每行代码的长度
要尽可能地保证代码长度不超过80个字符,如果代码行超过80应该折到下一行。
将参数分行输入,在开头简单地加入两个标准tab:
命名规范
名称中不允许使用混合的大小写字符。
局部变量如果能够清楚地表明它的用途,那么选取idx甚至是i这样的名称都是可行的。而像theLoopIndex这样冗长反复的名字不在接受之列。——匈牙利命名法(在变量名称中加入变量的类别)危害极大。
函数
根据经验函数的代码长度不应该超过两屏,局部变量不应该超过十个
1、一个函数应该功能单一并且实现精准。
2、将一个函数分解成一些更短小的函数的组合不会带来危害。——如果你担心函数调用导致的开销,可以使用inline关键字。
注释
一般情况下,注释的目的是描述你的代码要做什么和为什么要做,而不是具体通过什么方式实现的。怎么实现应该由代码本身展现。
注释不应该包含谁写了那个函数,修改日期和其他那些琐碎而无实际意义的内容。这些信息应该集中在文件最开头地方。
内核中一条注释看起来如下:
重要信息常常以“XXX:”开头,而bug通常以“FIXME"开头,就像:
总结
希望这篇博客对大家有所帮助!
更详尽的内容,请看"Linux 内核代码规范原文"
Linus 内部代码规范原文Linux kernel coding styleThis is a short document describing the preferred coding style for thelinux kernel.  Coding style is very personal, and I won't _force_ myviews on anybody, but this is what goes for anything that I have to beable to maintain, and I'd prefer it for most other things too.  Please
 at least consider the points made here.First off, I'd suggest printing out a copy of the GNU coding standards,and NOT read it.  Burn them, it's 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 to 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 you've been lookingat your screen for 20 straight hours, you'll find it a 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 indentation, you're screwed anyway, and should fix
 your program.In short, 8-char indents make things easier to read, and have the addedbenefit of warning you when you're nesting your functions too deep.
 Heed that warning.The preferred way to ease multiple indentation levels in a switch statement isto align the "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 <<= 10;/* fall through */default:break;}Don't put multiple statements on a single line unless you have
 something to hide:if (condition) do_this;do_something_everytime;Don't put multiple assignments on a single line either.  Kernel coding styleis super simple.  Avoid tricky expressions.Outside of comments, documentation and except in Kconfig, spaces are neverused for indentation, and the above example is deliberately broken.Get a decent editor and don't leave whitespace at the end of lines.
 Chapter 2: Breaking long lines and stringsCoding style is all about readability and maintainability using commonlyavailable tools.The limit on the length of lines is 80 columns and this is a stronglypreferred limit.Statements longer than 80 columns will be broken into sensible chunks, unlessexceeding 80 columns significantly increases readability and does not hideinformation. Descendants are always substantially shorter than the parent andare placed substantially to the right. The same applies to function headerswith a long argument list. However, never break user-visible strings such asprintk messages, because that breaks the ability to grep for them.Chapter 3: Placing Braces and SpacesThe other issue that always comes up in C styling is the placement ofbraces.  Unlike the indent size, there are few technical reasons tochoose one placement strategy over the other, but the preferred way, asshown to us by the prophets Kernighan and Ritchie, is to put the openingbrace last on the line, and put the closing brace first, thusly:if (x is true) {we do y}This applies to all non-function statement blocks (if, switch, for,while, do).  E.g.:switch (action) {case KOBJ_ADD:return "add";case KOBJ_REMOVE:return "remove";case KOBJ_CHANGE:return "change";default:return NULL;}However, there is one special case, namely functions: they have theopening brace at the beginning of the next line, thus:int function(int x){body of function}Heretic people all over the world have claimed that this inconsistencyis ...  well ...  inconsistent, but all right-thinking people know that(a) K&R are _right_ and (b) K&R are right.  Besides, functions arespecial anyway (you can't nest them in C).
 Note that the closing brace is empty on a line of its own, _except_ inthe cases where it is followed by a continuation of the same statement,ie a "while" in a do-statement or an "else" in an if-statement, likethis:do {body of do-loop} while (condition);andif (x == y) {..} else if (x > y) {...} else {....}Rationale: K&R.Also, note that this brace-placement also minimizes the number of empty(or almost empty) 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_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.  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" after"struct fileinfo info;" is declared).So use a space after 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, thepreferred 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:=  +  -  <  >  *  /  %  |  &  ^  <=  >=  ==  !=  ?  :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 whitespace at the ends of lines.  Some editors with"smart" 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 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 changing 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 moredifficult 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 functionthat counts the number of active users, you should call that"count_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 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 about 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 don't use things like "vps_t".
 It's a _mistake_ to use typedef for structures and pointers. When you see a
 vps_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 is actively used to _hide_what the object is).Example: "pte_t" etc. opaque objects that you can only access usingthe 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 therereally is absolutely _zero_ portably accessible information there.(b) Clear integer types, where the abstraction _helps_ avoid confusionwhether it is "int" or "long".u8/u16/u32 are perfectly fine typedefs, although they fit intocategory (d) better than here.NOTE! Again - there needs to be a _reason_ for this. If something is"unsigned long", then there's no reason to do
 typedef unsigned long myflags_t;but if there is a clear reason for why it under certain circumstancesmight 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 _new_ type fortype-checking.(d) New types which are identical to standard C99 types, in certainexceptional circumstances.Although it would only take a short amount of time for the eyes andbrain to become accustomed to the standard types like 'uint32_t',some people object to their use anyway.Therefore, the Linux-specific 'u8/u16/u32/u64' types and theirsigned equivalents which are identical to standard types arepermitted -- although they are not mandatory in new code of yourown.When editing existing code which already uses one or the other setof types, you should conform to the existing choices in that code.(e) Types safe for use in userspace.In certain structures which are visible to userspace, we cannotrequire C99 types and cannot use the 'u32' form above. Thus, weuse __u32 and similar types in all structures which are sharedwith userspace.Maybe there are other cases too, but the rule should basically be to NEVEREVER use a typedef unless you can clearly match one of those rules.In general, a pointer, or a struct that has elements that can reasonablybe directly accessed should _never_ be a typedef.Chapter 6: FunctionsFunctions should be short and sweet, and do just one thing.  They shouldfit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,as we all know), and do one thing and do that well.The maximum length of a function is inversely proportional to thecomplexity and indentation level of that function.  So, if you have aconceptually simple function that is just one long (but simple)case-statement, where you have to do lots of small things for a lot ofdifferent cases, it's OK to have a longer function.
 However, if you have a complex function, and you suspect that aless-than-gifted first-year high-school student might not evenunderstand what the function is all about, you should adhere to themaximum limits all the more closely.  Use helper functions withdescriptive names (you can ask the compiler to in-line them if you thinkit's performance-critical, and it will probably do a better job of it
 than you would have done).Another measure of the function is the number of local variables.  Theyshouldn't exceed 5-10, or you're doing something wrong.  Re-think thefunction, and split it into smaller pieces.  A human brain cangenerally easily keep track of about 7 different things, anything moreand it gets confused.  You know you're brilliant, but maybe you'd liketo understand what you did 2 weeks from now.In source files, separate functions with one blank line.  If the function isexported, the EXPORT* macro for it should follow immediately after the closingfunction brace line.  E.g.:int system_is_up(void){return system_state == SYSTEM_RUNNING;}EXPORT_SYMBOL(system_is_up);In function prototypes, include parameter names with their data types.Although this is not required by the C language, it is preferred in Linuxbecause it is a simple way to add valuable information for the reader.Chapter 7: Centralized exiting of functionsAlbeit deprecated by some people, the equivalent of the goto statement isused frequently by compilers in form of the unconditional jump instruction.The goto statement comes in handy when a function exits from multiplelocations and some common work such as cleanup has to be done.The rationale is:- unconditional statements are easier to understand and follow- nesting is reduced- errors by not updating individual exit points when makingmodifications are prevented- saves the compiler work to optimize redundant code away ;)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;}Chapter 8: CommentingComments are good, but there is also a danger of over-commenting.  NEVERtry to explain HOW your code works in a comment: it's much better towrite the code so that the _working_ is obvious, and it's a waste of
 time to explain badly written code.Generally, you want your comments to tell WHAT your code does, not HOW.Also, try to avoid putting comments inside a function body: if thefunction is so complex that you need to separately comment parts of it,you should probably go back to chapter 6 for a while.  You can makesmall comments to note or warn about something particularly clever (orugly), but try to avoid excess.  Instead, put the comments at the headof the function, telling people what it does, and possibly WHY it doesit.When commenting the kernel API functions, please use the kernel-doc format.See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-docfor details.Linux style for comments is the C89 "/* ... */" style.Don't use C99-style "// ..." comments.
 The preferred style for long (multi-line) comments is:/** This is the preferred style for multi-line* comments in the Linux kernel source code.* Please use it consistently.** Description:  A column of asterisks on the left side,* with beginning and ending almost-blank lines.*/For files in net/ and drivers/net/ the preferred style for long (multi-line)comments is a little different./* The preferred comment style for files in net/ and drivers/net* looks like this.** It is nearly the same as the generally preferred comment style,* but there is no initial almost-blank line.*/It's also important to comment data, whether they are basic types or derivedtypes.  To this end, use just one data declaration per line (no commas formultiple data declarations).  This leaves you room for a small comment on eachitem, explaining its use.Chapter 9: You've made a mess of it
 That's OK, we all do.  You've probably been told by your long-time Unixuser helper that "GNU emacs" automatically formats the C sources foryou, and you've noticed that yes, it does do that, but the defaults ituses are less than desirable (in fact, they are worse than randomtyping - an infinite number of monkeys typing into GNU emacs would nevermake a good program).So, you can either get rid of GNU emacs, or change it to use sanervalues.  To do the latter, you can stick the following in your .emacs file:(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-nonemptyc-lineup-gcc-asm-regc-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")))))This will make emacs go better with the kernel coding style for Cfiles below ~/src/linux-trees.But even if you fail in getting emacs to do sane formatting, noteverything is lost: use "indent".Now, again, GNU indent has the same brain-dead settings that GNU emacshas, which is why you need to give it a few command line options.However, that's not too bad, because even the makers of GNU indentrecognize the authority of K&R (the GNU people aren't evil, they arejust severely misguided in this matter), so you just give indent theoptions "-kr -i8" (stands for "K&R, 8 character indents"), or use"scripts/Lindent", which indents in the latest style."indent" has a lot of options, and especially when it comes to commentre-formatting you may want to take a look at the man page.  Butremember: "indent" is not a fix for bad programming.Chapter 10: Kconfig configuration filesFor all of the Kconfig* configuration files throughout the source tree,the indentation is somewhat different.  Lines under a "config" definitionare indented with one tab, while help text is indented an additional twospaces.  Example:config AUDITbool "Auditing support"depends on NEThelpEnable auditing infrastructure that can be used with anotherkernel subsystem, such as SELinux (which requires this forlogging of avc messages output).  Does not do system-callauditing without CONFIG_AUDITSYSCALL.Features that might still be considered unstable should be defined asdependent on "EXPERIMENTAL":config SLUBdepends on EXPERIMENTAL && !ARCH_USES_SLAB_PAGE_STRUCTbool "SLUB (Unqueued Allocator)"...while seriously dangerous features (such as write support for certainfilesystems) should advertise this prominently in their prompt string:config ADFS_FS_RWbool "ADFS write support (DANGEROUS)"depends on ADFS_FS...For full documentation on the configuration files, see the fileDocumentation/kbuild/kconfig-language.txt.Chapter 11: Data structuresData structures that have visibility outside the single-threadedenvironment they are created and destroyed in should always havereference counts.  In the kernel, garbage collection doesn't exist (andoutside the kernel garbage collection is slow and inefficient), whichmeans that you absolutely _have_ to reference count all your uses.Reference counting means that you can avoid locking, and allows multipleusers to have access to the data structure in parallel - and not havingto worry about the structure suddenly going away from under them justbecause they slept or did something else for a while.Note that locking is _not_ a replacement for reference counting.Locking is used to keep data structures coherent, while referencecounting is a memory management technique.  Usually both are needed, andthey are not to be confused with each other.Many data structures can indeed have two levels of reference counting,when there are users of different "classes".  The subclass count countsthe number of subclass users, and decrements the global count just oncewhen the subclass count goes to zero.Examples of this kind of "multi-level-reference-counting" can be found inmemory management ("struct mm_struct": mm_users and mm_count), and infilesystem code ("struct super_block": s_count and s_active).Remember: if another thread can find your data structure, and you don't
 have a reference count on it, you almost certainly have a bug.Chapter 12: Macros, Enums and RTLNames of macros defining constants and labels in enums are capitalized.#define CONSTANT 0x12345Enums are preferred when defining several related constants.CAPITALIZED macro names are appreciated but macros resembling functionsmay be named in lower case.Generally, inline functions are preferable to macros resembling functions.Macros with multiple statements should be enclosed in a do - while block:#define macrofun(a, b, c)             \do {                    \if (a == 5)            \do_this(b, c);        \} while (0)Things to avoid when using macros:1) macros that affect control flow:#define FOO(x)                    \do {                    \if (blah(x) < 0)        \return -EBUGGERED;    \} while(0)is a _very_ bad idea.  It looks like a function call but exits the "calling"function; don't break the internal parsers of those who will read the code.2) macros that depend on having a local variable with a magic name:#define FOO(val) bar(index, val)might look like a good thing, but it's confusing as hell when one reads thecode and it's prone to breakage from seemingly innocent changes.3) macros with arguments that are used as l-values: FOO(x) = y; willbite you if somebody e.g. turns FOO into an inline function.4) forgetting about precedence: macros defining constants using expressionsmust enclose the expression in parentheses. Beware of similar issues withmacros using parameters.#define CONSTANT 0x4000#define CONSTEXP (CONSTANT | 3)The cpp manual deals with macros exhaustively. The gcc internals manual alsocovers RTL which is used frequently with assembly language in the kernel.Chapter 13: Printing kernel messagesKernel developers like to be seen as literate. Do mind the spellingof kernel messages to make a good impression. Do not use crippledwords like "dont"; use "do not" or "don't" instead.  Make the messagesconcise, clear, and unambiguous.Kernel messages do not have to be terminated with a period.Printing numbers in parentheses (%d) adds no value and should be avoided.There are a number of driver model diagnostic macros in <linux/device.h>which you should use to make sure messages are matched to the right deviceand driver, and are tagged with the right level:  dev_err(), dev_warn(),dev_info(), and so forth.  For messages that aren't associated with aparticular device, <linux/printk.h> defines pr_debug() and pr_info().Coming up with good debugging messages can be quite a challenge; and onceyou have them, they can be a huge help for remote troubleshooting.  Suchmessages should be compiled out when the DEBUG symbol is not defined (thatis, by default they are not included).  When you use dev_dbg() or pr_debug(),that's automatic.  Many subsystems have Kconfig options to turn on -DDEBUG.
 A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to theones already enabled by DEBUG.Chapter 14: Allocating memoryThe kernel provides the following general purpose memory allocators:kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), andvzalloc().  Please refer to the API documentation for further informationabout them.The preferred form for passing a size of a struct is the following:p = kmalloc(sizeof(*p), ...);The alternative form where struct name is spelled out hurts readability andintroduces an opportunity for a bug when the pointer variable type is changedbut the corresponding sizeof that is passed to a memory allocator is not.Casting the return value which is a void pointer is redundant. The conversionfrom void pointer to any other pointer type is guaranteed by the C programminglanguage.The preferred form for allocating an array is the following:p = kmalloc_array(n, sizeof(...), ...);The preferred form for allocating a zeroed array is the following:p = kcalloc(n, sizeof(...), ...);Both forms check for overflow on the allocation size n * sizeof(...),and return NULL if that occurred.Chapter 15: The inline diseaseThere appears to be a common misperception that gcc has a magic "make mefaster" speedup option called "inline". While the use of inlines can beappropriate (for example as a means of replacing macros, see Chapter 12), itvery often is not. Abundant use of the inline keyword leads to a much biggerkernel, which in turn slows the system as a whole down, due to a biggericache footprint for the CPU and simply because there is less memoryavailable for the pagecache. Just think about it; a pagecache miss causes adisk seek, which easily takes 5 milliseconds. There are a LOT of cpu cyclesthat can go into these 5 milliseconds.A reasonable rule of thumb is to not put inline at functions that have morethan 3 lines of code in them. An exception to this rule are the cases wherea parameter is known to be a compiletime constant, and as a result of thisconstantness you *know* the compiler will be able to optimize most of yourfunction away at compile time. For a good example of this later case, seethe kmalloc() inline function.Often people argue that adding inline to functions that are static and usedonly once is always a win since there is no space tradeoff. While this istechnically correct, gcc is capable of inlining these automatically withouthelp, and the maintenance issue of removing the inline when a second userappears outweighs the potential value of the hint that tells gcc to dosomething it would have done anyway.Chapter 16: Function return values and namesFunctions can return values of many different kinds, and one of themost common is a value indicating whether the function succeeded orfailed.  Such a value can be represented as an error-code integer(-Exxx = failure, 0 = success) or a "succeeded" boolean (0 = failure,non-zero = success).Mixing up these two sorts of representations is a fertile source ofdifficult-to-find bugs.  If the C language included a strong distinctionbetween integers and booleans then the compiler would find these mistakesfor us... but it doesn't.  To help prevent such bugs, always follow this
 convention:If the name of a function is an action or an imperative command,the function should return an error-code integer.  If the nameis a predicate, the function should return a "succeeded" boolean.For example, "add work" is a command, and the add_work() function returns 0for success or -EBUSY for failure.  In the same way, "PCI device present" isa predicate, and the pci_dev_present() function returns 1 if it succeeds infinding a matching device or 0 if it doesn't.
 All EXPORTed functions must respect this convention, and so should allpublic functions.  Private (static) functions need not, but it isrecommended that they do.Functions whose return value is the actual result of a computation, ratherthan an indication of whether the computation succeeded, are not subject tothis rule.  Generally they indicate failure by returning some out-of-rangeresult.  Typical examples would be functions that return pointers; they useNULL or the ERR_PTR mechanism to report failure.Chapter 17:  Don't re-invent the kernel macros
 The header file include/linux/kernel.h contains a number of macros thatyou should use, rather than explicitly coding some variant of them yourself.For example, if you need to calculate the length of an array, take advantageof the macro#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))Similarly, if you need to calculate the size of some structure member, use#define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f))There are also min() and max() macros that do strict type checking if youneed them.  Feel free to peruse that header file to see what else is alreadydefined that you shouldn't reproduce in your code.
 Chapter 18:  Editor modelines and other cruftSome editors can interpret configuration information embedded in source files,indicated with special markers.  For example, emacs interprets lines markedlike this:-*- mode: c -*-Or like this:/*Local Variables:compile-command: "gcc -DMAGIC_DEBUG_FLAG foo.c"End:*/Vim interprets markers that look like this:/* vim:set sw=8 noet */Do not include any of these in source files.  People have their own personaleditor configurations, and your source files should not override them.  Thisincludes markers for indentation and mode configuration.  People may use theirown custom mode, or may have some other magic method for making indentationwork correctly.Chapter 19:  Inline assemblyIn architecture-specific code, you may need to use inline assembly to interfacewith CPU or platform functionality.  Don't hesitate to do so when necessary.However, don't use inline assembly gratuitously when C can do the job.  You canand should poke hardware from C when possible.Consider writing simple helper functions that wrap common bits of inlineassembly, rather than repeatedly writing them with slight variations.  Rememberthat inline assembly can use C parameters.Large, non-trivial assembly functions should go in .S files, with correspondingC prototypes defined in C header files.  The C prototypes for assemblyfunctions should use "asmlinkage".You may need to mark your asm statement as volatile, to prevent GCC fromremoving it if GCC doesn't notice any side effects.  You don't always need todo so, though, and doing so unnecessarily can limit optimization.When writing a single inline assembly statement containing multipleinstructions, put each instruction on a separate line in a separate quotedstring, and end each string except the last with \n\t to properly indent thenext instruction in the assembly output:asm ("magic %reg1, #42\n\t""more_magic %reg2, %reg3": /* outputs */ : /* inputs */ : /* clobbers */);Appendix I: ReferencesThe C Programming Language, Second Editionby Brian W. Kernighan and Dennis M. Ritchie.Prentice Hall, Inc., 1988.ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).URL: http://cm.bell-labs.com/cm/cs/cbook/
 The Practice of Programmingby Brian W. Kernighan and Rob Pike.Addison-Wesley, Inc., 1999.ISBN 0-201-61586-X.URL: http://cm.bell-labs.com/cm/cs/tpop/
 GNU manuals - where in compliance with K&R and this text - for cpp, gcc,gcc internals and indent, all available from http://www.gnu.org/manual/
 WG14 is the international standardization working group for the programminglanguage C, URL: http://www.open-std.org/JTC1/SC22/WG14/
 Kernel CodingStyle, by greg@kroah.com at OLS 2002:http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/

 

转载于:https://www.cnblogs.com/Leo-Forest/archive/2013/04/08/3007212.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/423713.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mybatis学习(54):鉴定器

数据库表 数据库叫blog_gp1701 author表 数据 blog表 数据 comment表 数据 post表 数据 vechcle 目录结构 jar包导入 先给对应的jar包导入 建立一个junit单元测试 配置文件 log4j.properties ### \u914D\u7F6E\u6839 ### log4j.rootLogger debug,console ,fileAppender…

hadoop fs:du统计hdfs文件(目录下文件)大小的用法

hadoop fs:du统计hdfs文件&#xff08;目录下文件&#xff09;大小的用法 hadoop fs 更多用法&#xff0c;请参考官网&#xff1a;http://hadoop.apache.org/docs/r1.0.4/cn/hdfs_shell.html 以下是我的使用统计文件时使用的记录&#xff1a; [tdv00938 ~]$ hadoop fs -ls /jc_…

sqoop操作之Oracle导入到HDFS

导入表的所有字段 sqoop import --connect jdbc:oracle:thin:192.168.1.100:1521:ORCL \ --username SCOTT --password tiger \ --table EMP -m 1; 查看执行结果&#xff1a; hadoop fs -cat /user/hadoop/EMP/part-m-00000 7369,SMITH,CLERK,7902,1980-12-17 00:00:00.0,800,n…

ps学习1:去除图片上的文字

首先我们看到如图所示的图&#xff0c;这个时候我们要给他右上角的文字去除 首先打开我们的ps工具--我登陆的在线ps教程 https://www.uupoop.com/ 点击编辑---填充 保存 完成修改

Java面试题16 牛客 以下java程序代码,执行后的结果是()

Java面试题16 牛客 以下java程序代码&#xff0c;执行后的结果是&#xff08;&#xff09; 1 2 3 4 5 6 7 8 9 10 public class Test { public static void main(String[] args) { Object o new Object() { public boolean equals(Object o…

Hive压缩说明

为什么要压缩 在Hive中对中间数据或最终数据做压缩&#xff0c;是提高数据吞吐量和性能的一种手段。对数据做压缩&#xff0c;可以大量减少磁盘的存储空间&#xff0c;比如基于文本的数据文件&#xff0c;可以将文件压缩40%或更多。同时压缩后的文件在磁盘间传输和I/O也会大大减…

kubelet源码学习(一):kubelet工作原理、kubelet启动过程

本文基于Kubernetes v1.22.4版本进行源码学习 1、kubelet工作原理 1&#xff09;、kubelet核心工作 kubelet的工作核心就是一个控制循环&#xff0c;即&#xff1a;SyncLoop&#xff08;图中的大圆圈&#xff09;。而驱动这个控制循环运行的事件&#xff0c;包括&#xff1a;P…

Java面试题18 牛客 假定Base b = new Derived();

Java面试题18 牛客 假定Base b new Derived&#xff08;&#xff09;; 调用执行b.methodOne&#xff08;&#xff09;后&#xff0c;输出结果是什么&#xff1f; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 public class Base { public…

ReactOS,硬件抽象层,HAL概述

分析环境reactos0.3.4 &#xff0c;i386体系] ReactOS的硬件抽象层 HAL(Hardware Abstraction Layer)位于OS与硬件的中间&#xff0c;和windows的hal原理基本一致&#xff0c;硬件抽象层隐藏特定平台的硬件接口细节&#xff0c;为上层的系统提供标准的稳定的虚拟硬件平台&…

[给ASP.NET 初学者的话]不要练功练了三年,才发现自己必须「砍掉重练」!....学习ASP.NET之前,请先把自己杯中的水倒掉...

这是我的文章备份&#xff0c;原文请看&#xff1a; [给ASP.NET 初学者的话]不要练功练了三年&#xff0c;才发现自己必须「砍掉重练」&#xff01;....学习ASP.NET之前&#xff0c;请先把自己杯中的水倒掉 http://www.dotblogs.com.tw/mis2000lab/archive/2012/03/15/game_ove…

Java面试题19 牛客下面有关java的引用类型,说法正确的有?

Java面试题19下面有关java的引用类型&#xff0c;说法正确的有&#xff1f; A:对于一个对象来说&#xff0c;只要有强引用的存在&#xff0c;它就会一直存在于内存中 B&#xff1a;如果一个对象仅持有虚引用&#xff0c;那么它就和没有任何引用一样&#xff0c;在任何时候都可…

MapReduce运行机制

相关链接 MapReduce中Shuffle机制详解——Map端Shuffle链接 MapReduce中Shuffle机制详解——Reduce端Shuffle链接MapReduce将作业job的整个运行过程分为两个阶段&#xff1a;Map阶段和Reduce阶段。按照时间顺序包括&#xff1a;输入分片&#xff08;input split&#xff09;、m…

WebService Software Factory 设计草图

以下是根据WSSF设计理念&#xff0c;按现公司的业务需求设计的接口项目拟稿&#xff0c;实现细分。仅供参考。&#xff08;WSSF---ASMX版&#xff09; 建议用1680*1050分辩浏览 转载于:https://www.cnblogs.com/RuiLei/archive/2008/10/05/1304160.html

Java面试题 20在面向对象编程里,经常使用is-a来说明对象之间的继承关系

Java面试题 20在面向对象编程里&#xff0c;经常使用is-a来说明对象之间的继承关系&#xff0c;下列对象中不具备继承关系的是&#xff1f;&#xff08;&#xff09; A:手机与小米手机 B&#xff1a;企业家与雷军 C:编程语言与Java D&#xff1a;中国与北京 类之间存在以下…

MapReduce计数器

原文链接&#xff1a;http://itfish.net/article/61067.html 1、MapReduce计数器是什么&#xff1f;计数器是用来记录job的执行进度和状态的。它的作用可以理解为日志。我们可以在程序的某个位置插入计数器&#xff0c;记录数据或者进度的变化情况。 2、MapReduce计数器能做什么…

编写“线围棋”程序-2-可开局

棋盘有了&#xff0c;怎么支持在上面落子呢&#xff1f; 只要解决下面3个问题就可以了&#xff1a; 1.响应鼠标点击事件&#xff0c;获得“下棋子”的动作源。 2.修改和记录棋局状态。 3.在棋盘上显示棋局的状态。 为此&#xff0c;直接增加一个“棋局类“&#xff0c;也就是对…

Java面试题 21 下列说法正确的有()

下列说法正确的有&#xff08;&#xff09; A 能被java.exe成功运行的java class文件必须有main()方法 B J2SDK就是Java API C:Appletviewer.exe可利用jar选项运行.jar文件 D能被Appletviewer成功运行的java class文件必须有main()方法 蒙蔽树上蒙蔽果&#xff0c;蒙蔽树下…

[翻译]SQL Server 未公开的两个存储过程sp_MSforeachtable 和 sp_MSforeachdb

SQL Server 未公开的两个存储过程sp_MSforeachtable 和 sp_MSforeachdb 您是否曾经写过代码来处理数据库中的所有表&#xff1f;处理一个 SQL Server实例中的所有数据库的代码又该如何写&#xff1f;然则&#xff0c;您是否知道有多种方法可以解决这问题&#xff1f;您可以创建…

Java面试题 22 牛客 Java是一门支持反射的语言,基于反射为Java提供了丰富的动态性支持

Java面试题 22 牛客 Java是一门支持反射的语言,基于反射为Java提供了丰富的动态性支持&#xff0c;下面关于Java反射的描述&#xff0c;哪些是错误的&#xff1a;( ) A Java反射主要涉及的类如Class, Method, Filed,等&#xff0c;他们都在java.lang.reflet包下 B 通…

java面试题24 关于Java中的数组,

java面试题24 关于Java中的数组&#xff0c;下面的一些描述&#xff0c;哪些描述是准确的&#xff1a;&#xff08; &#xff09; A 数组是一个对象&#xff0c;不同类型的数组具有不同的类 B 数组长度是可以动态调整的 C 数组是一个连续的存储结构 D:一个固定长度的…