Linux Coding Style (Collected)

[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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
编码风格是Verilog设计中非常重要的方面,它直接影响着代码的可维护性和可读性。以下是关于Verilog编码风格的一些建议: 1. 缩进和对齐:合理的缩进和对齐可以增加代码的可读性。建议使用4个空格进行缩进,并对相关的代码进行对齐,以便于理解代码结构。 2. 命名规范:命名应该具有描述性,能够准确反映信号或模块的功能。遵循一致的命名规范,可以使代码更易于理解和维护。可以使用驼峰命名法或下划线命名法。 3. 注释:适当的注释可以帮助其他人理解你的代码。在代码的关键部分添加注释,解释代码的功能、用途和设计思路。 4. 模块化设计:将代码分成多个小模块,每个模块只负责特定的功能。这样做可以增加代码的可复用性和可维护性。 5. 参数化设计:使用参数化的方式设计模块,可以提高代码的灵活性和可扩展性。通过将一些常量参数化,可以在实例化模块时灵活地调整参数的值。 6. 模块接口:在设计模块时,定义清楚模块的输入和输出接口,并确保适当的信号命名和位宽匹配。 7. 错误处理:编写代码时要考虑到可能出现的错误情况,并采取适当的错误处理机制,例如添加状态机或发送错误提示信号。 8. 使用阻塞和非阻塞赋值:在赋值时要使用适当的赋值操作符,阻塞赋值(=)用于组合逻辑,非阻塞赋值(<=)用于时序逻辑。 9. 适当使用常量和枚举:对于不会改变的数值,应该使用常量来定义。对于有限的状态集合或选项,可以使用枚举来增加代码的可读性。 10. 代码复用:适当的代码复用可以减少重复编写相似代码的工作量。可以使用模块、宏定义、函数等方式重新使用已有的代码块。 总的来说,编写Verilog代码时,需要注重代码的可读性、可维护性和灵活性,合理的编码风格将大大提高代码质量和工作效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值