1# RT-Thread 编程风格
2
3这是一份 RT-Thread 开发人员的开发指引。RT-Thread 做为一份开源软件,它需要由不同的人采用合作的方式完成,这份文档是开发人员的一个指引。RT-Thread 的开发人员请遵守这样的编程风格。同时对于使用 RT-Thread 的用户,也可通过这份文档了解 RT-Thread代码内部一些约定从而比较容易的把握到 RT-Thread 的实现方式。
4
5## 1.目录名称
6
7目录名称如果无特殊的需求,请使用全小写的形式;目录名称应能够反映部分的意思,例如各芯片移植由其芯片名称构成或芯片类别构成;components 目录下能够反映组件的意义。
8
9## 2.文件名称
10
11文件名称如果无特殊的需求(如果是引用其他地方,可以保留相应的名称),请使用全小写的形式。另外为了避免文件名重名的问题,一些地方请尽量不要使用通用化、使用频率高的名称。
12
13设备驱动源码文件:`drv_class.c` 的命名方式,如:
14
15- drv_spi.c
16- drv_gpio.c
17
18## 3.头文件定义
19
20C 语言头文件为了避免多次重复包含,需要定义一个符号。这个符号的定义形式请采用如下的风格:
21
22```c
23    #ifndef __FILE_H__
24    #define __FILE_H__
25    /* header file content */
26    #endif
27```
28
29即定义的符号两侧采用 "__" 以避免重名,另外也可以根据文件名中是否包含多个词语而采用 "_" 连接起来。
30
31## 4.文件头注释
32
33在每个源文件文件头上,应该包括相应的版权信息,Change Log 记录:
34
35```c
36/*
37 * Copyright (c) 2006-2020, RT-Thread Development Team
38 *
39 * SPDX-License-Identifier: Apache-2.0
40 *
41 * Change Logs:
42 * Date           Author       Notes
43 * 2006-03-18     Bernard      the first version
44 * 2006-04-26     Bernard      add semaphore APIs
45 */
46```
47
48例如采用如上的形式。
49
50## 5.结构体定义
51
52结构体名称请使用小写英文名的形式,单词与单词之间采用 "_" 连接,例如:
53
54```c
55    struct rt_list_node
56    {
57        struct rt_list_node *next;
58        struct rt_list_node *prev;
59    };
60```
61
62其中,**"{","}" 独立占用一行**,后面的成员定义使用缩进的方式定义。
63
64结构体等的类型定义请以结构体名称加上 "_t" 的形式作为名称,例如:
65
66```c
67    typedef struct rt_list_node rt_list_t;
68```
69
70因为内核中对象引用方便的缘故,采用了对象内核指针作为类型定义的形式,例如:
71
72```c
73    typedef struct rt_timer* rt_timer_t;
74```
75
76## 6.宏定义
77
78在RT-Thread中,请使用大写英文名称作为宏定义,单词之间使用 "_" 连接,例如:
79
80```c
81    #define RT_TRUE                         1
82```
83
84## 7.函数名称、声明
85
86函数名称请使用小写英文的形式,单词之间使用 "_" 连接。提供给上层应用使用的 API接口,必须在相应的头文件中声明;如果函数入口参数是空,必须使用 void 作为入口参数,例如:
87
88```c
89rt_thread_t rt_thread_self(void);
90```
91
92内部静态函数命名:以下划线开头,使用 `_class_method` 格式,不携带`_rt_`开头,如内核或驱动文件中的函数命名:
93
94```c
95/* IPC object init */
96static rt_err_t _ipc_object_init()
97
98/* UART driver ops */
99static rt_err_t _uart_configure()
100static rt_err_t _uart_control()
101```
102
103调用注册设备接口的函数命名:使用 `rt_hw_class_init()` 格式,举例:
104
105```c
106int rt_hw_uart_init(void)
107int rt_hw_spi_init(void)
108```
109
110## 8.注释编写
111
112请使用**英文**做为注释,使用中文注释将意味着在编写代码时需要来回不停的切换中英文输入法从而打断编写代码的思路。并且使用英文注释也能够比较好的与中国以外的技术者进行交流。
113
114**语句注释**:
115
116源代码的注释不应该过多,更多的说明应该是代码做了什么,仅当个别关键点才需要一些相应提示性的注释以解释一段复杂的算法它是如何工作的。对语句的注释只能写在它的**上方或右方**,其他位置都是非法的。
117
118```c
119/* 你的英文注释 */
120```
121
122**函数注释**:
123
124注释以 `/**` 开头,以 `  */` 结尾,中间写入函数注释,组成元素如下,每个元素描述之间空一行,且首列对齐:
125
126- @brief + 简述函数作用。在描述中,着重说明该函数的作用,每句话首字母大写,句尾加英文句号。
127- @note + 函数说明。在上述简述中未能体现到的函数功能或作用的一些点,可以做解释说明,每句话首字母大写,句尾加英文句号。
128- @see + 相关 API 罗列。若有与当前函数相关度较高的 API,可以进行列举。
129- @param + 以参数为主语 + be 动词 + 描述,说明参数的意义或来源。
130- @return + 枚举返回值 + 返回值的意思,若返回值为数据,则直接介绍数据的功能。
131- @warning + 函数使用注意要点。在函数使用时,描述需要注意的事项,如使用环境、使用方式等。每句话首字母大写,句尾加英文句号。
132
133注释模版请参见:rt-thread/src/ipc.c 源码文件,英文注释请参考使用 grammarly 以及谷歌翻译。
134
135```C
136/**
137 * @brief    The function will initialize a static event object.
138 *
139 * @note     For the static event object, its memory space is allocated by the compiler during compiling,
140 *           and shall placed on the read-write data segment or on the uninitialized data segment.
141 *           By contrast, the rt_event_create() function will allocate memory space automatically
142 *           and initialize the event.
143 *
144 * @see      rt_event_create()
145 *
146 * @param    event is a pointer to the event to initialize. It is assumed that storage for the event
147 *           will be allocated in your application.
148 *
149 * @param    name is a pointer to the name that given to the event.
150 *
151 * @param    value is the initial value for the event.
152 *           If want to share resources, you should initialize the value as the number of available resources.
153 *           If want to signal the occurrence of an event, you should initialize the value as 0.
154 *
155 * @param    flag is the event flag, which determines the queuing way of how multiple threads wait
156 *           when the event is not available.
157 *           The event flag can be ONE of the following values:
158 *
159 *               RT_IPC_FLAG_PRIO          The pending threads will queue in order of priority.
160 *
161 *               RT_IPC_FLAG_FIFO          The pending threads will queue in the first-in-first-out method
162 *                                         (also known as first-come-first-served (FCFS) scheduling strategy).
163 *
164 *               NOTE: RT_IPC_FLAG_FIFO is a non-real-time scheduling mode. It is strongly recommended to
165 *               use RT_IPC_FLAG_PRIO to ensure the thread is real-time UNLESS your applications concern about
166 *               the first-in-first-out principle, and you clearly understand that all threads involved in
167 *               this event will become non-real-time threads.
168 *
169 * @return   Return the operation status. When the return value is RT_EOK, the initialization is successful.
170 *           If the return value is any other values, it represents the initialization failed.
171 *
172 * @warning  This function can ONLY be called from threads.
173 */
174rt_err_t rt_event_init(rt_event_t event, const char *name, rt_uint8_t flag)
175{
176   ...
177}
178```
179
180## 9.缩进及分行
181
182缩进请采用 4 个空格的方式。如果没有什么特殊意义,请在 "{" 后进行分行,并在下一行都采用缩进的方式,例如:
183
184```c
185    if (condition)
186    {
187        /* others */
188    }
189```
190
191唯一的例外是 switch 语句,switch-case 语句采用 case 语句与 switch 对齐的方式,例如:
192
193```c
194    switch (value)
195    {
196    case value1:
197        break;
198    }
199```
200
201case 语句与前面的 switch 语句对齐,后续的语句则采用缩进的方式。分行上,如果没有什么特殊考虑,请**不要在代码中连续使用两个以上的空行**。
202
203## 10.大括号与空格
204
205从代码阅读角度,建议每个大括号单独占用一行,而不是跟在语句的后面,例如:
206
207```c
208    if (condition)
209    {
210        /* others */
211    }
212```
213
214匹配的大括号单独占用一行,代码阅读起来就会有相应的层次而不会容易出现混淆的情况。空格建议在非函数方式的括号调用前留一个空格以和前面的进行区分,例如:
215
216```c
217    if (x <= y)
218    {
219        /* others */
220    }
221
222    for (index = 0; index < MAX_NUMBER; index ++)
223    {
224        /* others */
225    }
226```
227
228建议在括号前留出一个空格(涉及的包括 if、for、while、switch 语句),而运算表达式中,运算符与字符串间留一个空格。另外,不要在括号的表达式两侧留空格,例如:
229
230```c
231    if ( x <= y )
232    {
233        /* other */
234    }
235```
236
237这样括号内两侧的空格是不允许的。
238
239## 11.日志信息
240
241代码中多使用ulog的方式来输出日志,例如:
242
243```
244#define DBG_TAG "Driver"
245#define DBG_LVL DBG_INFO
246#include <rtdbg.h>
247
248LOG_D("this is a debug log.");
249```
250
251- 在 RT-Thread 中,普遍使用的日志输出方式是通过`LOG_D` 、`LOG_I` 、`LOG_W` 、`LOG_E`的方式来输出日志,同时它也可以通过DBG_TAG来区分日志类别,DBG_LVL控制日志输出的等级。
252- 日志应该是以输出易懂易定位问题的方式。"天书式"的日志系统是糟糕的,不合理的,不应该出现在代码中。
253- 禁止在头文件中重定义DBG_TAG,防止其他模块包含时DBG_TAG出现不可控。
254- 严禁在timer或者中断打印大量日志,尽可能的避免或轻量化。
255- 不建议使用rt_kprintf来作为日志输出方式,rt_kprintf一般作为终端命令行交互使用。
256
257## 12.函数
258
259在内核编程中,函数应该尽量精简,仅完成相对独立的简单功能。函数的实现不应该太长,函数实现太长,应该反思能够如何修改(或拆分)使得函数更为精简、易懂。
260
261## 13.对象
262
263RT-Thread 内核采用了 C 语言对象化技术,命名表现形式是:对象名结构体表示类定义、对象名 + 动词短语形式表示类方法,例如:
264
265```c
266    struct rt_timer
267    {
268        struct rt_object parent;
269        /* other fields */
270    };
271    typedef struct rt_timer* rt_timer_t;
272```
273
274结构体定义 rt_timer 代表了 timer 对象的类定义;
275
276```c
277rt_timer_t rt_timer_create(const char* name,
278                           void (*timeout)(void* parameter),
279                           void* parameter,
280                           rt_tick_t time, rt_uint8_t flag);
281rt_err_t rt_timer_delete(rt_timer_t timer);
282rt_err_t rt_timer_start(rt_timer_t timer);
283rt_err_t rt_timer_stop(rt_timer_t timer);
284```
285
286rt_timer + 动词短语的形式表示能够应用于 timer 对象的方法。
287
288在创建一个新的对象时,应该思考好,对象的内存操作处理:是否允许一个静态对象存在,或仅仅支持从堆中动态分配的对象。
289
290## 14.格式化代码
291
292格式化代码是指通过脚本自动整理你的代码,并使其符合 RT-Thread 的编码规范。本文提供以下两种自动格式化代码方法,可以自行选择或配合使用。
293
294### 使用 astyle 格式化
295
296用 astyle 自动格式化代码,参数如下:
297
298          --style=allman
299          --indent=spaces=4
300          --indent-preproc-block
301          --pad-oper
302          --pad-header
303          --unpad-paren
304          --suffix=none
305          --align-pointer=name
306          --lineend=linux
307          --convert-tabs
308          --verbose
309
310能满足函数空格、缩进、函数语句等的规范。
311
312### 使用 formatting 格式化
313
314使用 [formatting](https://github.com/mysterywolf/formatting) 扫描文件来格式化代码:formatting 可以满足编码规则的基本要求,如:
315
316- 将源文件编码统一为 UTF-8
317- 将 TAB 键替换为 4 空格
318- 将每行末尾多余的空格删除,并统一换行符为 '\n'
319