Linux Coding Style (Collected)

来源:互联网 发布:thug life软件 编辑:程序博客网 时间:2024/06/04 01:36

[doc]

Linux Coding Style


You can find the Linux Coding Style here.It is brief but really uncomfortable to read it , that what i am going to do here. Just List some significance point and little interpretations.


1.Indentation

  • Tabs are 8 characters, and indentations are also 8 characters Tab.

Maybe you’ll say the code is move too far to the right. The answer to that is that if you need more than 3 levels of indentation, you’re screwed anyway, and should fix your program.

In short, 8-char indents make things easier to read.

/* * all indentation is 8-char-tab. */    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
    if (condition) do_this;
  • Don’t put multiple assignments on a single line

  • spaces are never used for indentation(use tabs)

  • Don’t leave whitespace at the end of lines


2.Breaking long lines and strings

  • The limit on the length of lines is 80 columns

  • never break user-visible strings


3.Placing Braces and Spaces

Braces

  • put the opening brace last on the line, and put the closing brace first

    The other issue that always comes up in C styling is the placement of braces. Unlike the indent size, there are few technical reasons to choose one placement strategy over the other, but the preferred way, as shown to us by the prophets Kernighan and Ritchie, is to put the opening brace 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 the
opening brace at the beginning of the next line, thus:

    int function(int x)    {        body of function    }
  • closing brace is empty on a line of its own, except:
    do {        body of do-loop    } while (condition);

and

    if (x == y) {        ..    } else if (x > y) {        ...    } else {        ....    }
  • Do not unnecessarily use braces where a single statement will do.
if (condition)        action();

and

    if (condition)        do_this();    else        do_that();

spaces

  • Use a space after (most) keywords.

    Use a space after (most) keywords. The notable exceptions are sizeof, typeof, alignof, and __attribute__, which look somewhat like functions
    So use a space after these keywords:

    if, switch, case, for, do, while

but 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 ); /* BAD style */
  • Let the ‘*’ adjacent to the data or function name

    example:

    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__  defined

no 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.

4.Naming

  • GLOBAL variables need to have descriptive names

    GLOBAL variables (to be used only if you really need them) need to have descriptive names, as do global functions. If you have a function that counts the number of active users, you should call that count_active_users() or similar, you should not call it cntusr()

  • LOCAL variable names should be short, and to the point

    if you have some random integer loop counter, it should probably be called “i”. Calling it “loop_counter” is non-productive, if there is no chance of it being mis-understood. Similarly, “tmp” can be just about any type of variable that is used to hold a temporary value.

5.Typedefs

  • It’s a mistake to use typedef for structures and pointers.

Please 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 says

    struct virtual_container *a;

you can actually tell what “a” is.


6.Functions

  • Functions should be short and sweet, and do just one thing

  • the number of local variables shouldn’t exceed 5-10

  • separate functions with one blank line.

  • In function prototypes, include parameter names with their data types


7.Centralized exiting of functions

Choose label names which say what the goto does or why the goto exists. An example of a good name could be “out_buffer:” if the goto frees “buffer”. Avoid using GW-BASIC names like “err1:” and “err2:”. Also don’t name them after the goto location like “err_kmalloc_failed:”

The rationale for using gotos is:

  • unconditional statements are easier to understand and follow
  • nesting is reduced
  • errors by not updating individual exit points when making
    modifications are prevented
  • saves the compiler work to optimize redundant code away ;)
    int fun(int a)    {        int result = 0;        char *buffer;        buffer = kmalloc(SIZE, GFP_KERNEL);        if (!buffer)            return -ENOMEM;        if (condition1) {            while (loop1) {                ...            }            result = 1;            goto out_buffer;        }        ...    out_buffer:        kfree(buffer);        return result;    }

8.commenting

  • tell WHAT your code does, not HOW.

  • When commenting the kernel API functions, please use the kernel-doc format

  • 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.     */

9. Vim Set Linux Formatting

Downloads the zip file from github. and drop the plugin (which is named linuxsty.vim) into your vim configuration directory. I put it into “~/.vim/”. Don’t worry, it’ll not replace your own configurations, when you want to code linux code ,just type “SetLinuxFormatting” in the command line of vim.
https://github.com/bhilburn/kernel-coding-style

10.Macros, Enums and RTL

  • CAPITALIZED macro names are appreciated but macros resembling functions may be named in lower case.
    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 the
code and it’s prone to breakage from seemingly innocent changes.

3.macros with arguments that are used as l-values:

FOO(x) = y; 

will bite you if somebody e.g. turns FOO into an inline function.

4.forgetting about precedence: macros defining constants using expressions
must enclose the expression in parentheses. Beware of similar issues with macros using parameters.

    #define CONSTANT 0x4000    #define CONSTEXP (CONSTANT | 3)

5.namespace collisions when defining local variables in macros resembling

#define FOO(x)              \({                          \    typeof(x) ret;          \    ret = calc_ret(x);      \        (ret);          \})  

11.Allocating memory

The preferred form for passing a size of a struct is the following:

    p = kmalloc(sizeof(*p), ...);

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(...), ...);
0 0
原创粉丝点击