DPDK的代码规范

每个公司都会有自己代码风格或者编程规范,都旨在防范编程语言的一些陷阱或者提高代码效率,还有就是保持一致编码风格来提高代码可读性,方便code review;

或者说代码的一种美学,比如python也就有pep8约定,还有一些精致编码来表示你是否Pythonic。

DPDK也有自己的编码风格,看完颇有受益,这里提取一些个人比较喜欢的风格来参考,尤其是关于结构体部分。

1、注释风格,参考doxygen的使用

单行注释:

/*
* VERY important single-line comments look like this.
*/

或者

/* Most single-line comments look like this. */

多行注释:

/*
* Multi-line comments look like this. Make them real sentences. Fill
* them so they look like real paragraphs.
*/

2、头文件包含

标准库和dpdk提供的库头文件都使用<>包含,其他应用程序的头文件都使用 ""包含

1 #include <stdio.h>
2 #include <rte_eal.h>
3 #include "application.h" 

3、预编译头

1 #ifndef _FILE_H_
2 #define _FILE_H_
3 /* Code */
4 #endif /* _FILE_H_ */

4、结构体定义

(1)声明结构体成员变量的时候,首先按方便使用排序,然后按字节大小排序(从大到小),然后再按字典表排序,并且考虑最小的字节填充来保证字节对齐。

      按方便使用排序是意思是把常用的成员变量放在一起,突出整个结构体的逻辑性

(2)对于已经声明好的结构体,如果要添加新的成员,应该添加在结构体的尾部来保证向后兼容,但我个人觉得这个在遵守第(1)条的情况下,才考虑这条。

(3)结构体的每个元素都应该在单独的一行。

(4)成员变量的类型起始对齐,变量名使用空格对齐第一个字符。

(5)对于类型特别长的变量,不方便对齐,就用一个空格的间隔书写。

1 struct foo {
2      struct foo     *next;            /* List of active foo. */
3      struct mumble  amumble;          /* Comment for mumble. */
4      int            bar;              /* Try to align the comments. */
5      struct verylongtypename *baz;    /* Won't fit with other members */
6 };

(6)结构体声明放在所使用文件的代码起始部分,或者在一个单独的头文件里,方便其他文件包含。

(7)变量的声明应该与结构体的声明分开,如果在头文件声明变量,应该使用extern。

(8)结构体的定义要避免名字空间冲突,需要加上特有的前缀,比如dpdk是 rte_ 。

5、使用linux的queue macro会比自己实现的list rolling要好。

1 #include <sys/queue.h>
2 struct foo {
3      LIST_ENTRY(foo) link;            /* Use queue macros for foo lists. */
4      struct mumble   amumble;         /* Comment for mumble. */
5      int             bar;             /* Try to align the comments. */
6      struct verylongtypename *baz;    /* Won't fit with other members */
7 };
8 LIST_HEAD(, foo) foohead; /* Head of global foo list. */

6、typedef的使用

 避免使用typedef来声明结构体类型。

如下声明

1 struct my_struct_type {
2 /* ... */
3 };
4 struct my_struct_type my_var;

比下面的好:

typedef struct my_struct_type {
/* ... */
} my_struct_type;
my_struct_type my_var

(1)typedef的问题是它会不恰当的隐藏原有的结构体类型。比如,你不知道它define的是结构体自身还是结构体的指针(有人可能会说通过类型+前缀/后缀来区分,众口难调,我也不喜欢那种如 int_ptr 之类的写法)

(2)typedef只能声明一次,而结构体可以通过不完整的形式声明多次,比如 struct my_struct_type

(3)要使用typedef的类型必须包含它所在的头文件,这个可能造成名词空间污染。

(4)不要使用define来替代typedef,会引起更多的问题,比如  #define pint  int * 就会出现连续的变量声明问题。

(5)推荐使用typedef来声明函数指针,可以提高代码可读性

1 /**
2 * Definition of a remote launch function.
3 */
4 typedef int (lcore_function_t)(void *);
5 /* launch a function of lcore_function_t type */
6 int rte_eal_remote_launch(lcore_function_t *f, void *arg, unsigned slave_id);
原文地址:https://www.cnblogs.com/danxi/p/6412590.html