docs/contribute/code.md
我们使用clang-format和git-clang-format统一C、C++、Objective-C代码风格。代码风格使用工程根目录下的.clang-format文件描述。
在新增文件时,使用clang-format调整代码风格:
clang-format -i /path/to/new_file
在修改文件时,使用git-clang-format调整新增部分的代码风格:
cd /path/to/MNN
git-clang-format
对于C、C++、Objective-C代码,我们使用Google代码风格。但是对下列项目作出调整:
| 项目 | 修改 |
|---|---|
| AccessModifierOffset 访问权限修正偏移 | 由-1改为-4 |
| AlignConsecutiveAssignments 连续赋值对齐 | 由false改为true |
| ColumnLimit 列宽限制 | 由80改为120 |
| IndentWidth 缩进宽度 | 由2改为4 |
| ObjCBlockIndentWidth ObjC Block缩进宽度 | 由2改为4 |
| ObjCSpaceAfterProperty ObjC属性后保留空格 | 由false改为true |
| SpacesBeforeTrailingComments 行尾注释前空格数 | 由2改为1 |
在C、C++和ObjC中使用驼峰命名法,如CityCat和bigDoghouse。
private、protected的成员变量,以m为前缀,如mCat;全局变量、类静态变量,以g为前缀,如gWorld;所有非static C函数、汇编函数都需要以MNN为前缀。
所有需要对外暴露的函数、类,都需要使用MNN_PUBLIC标记。
为降低内存泄露风险,申请临时内存和释放内存宜在相邻代码块内实现,即,应使用智能指针或AutoStorage类。
对于外部入参,应明确判定入参有效性,如:
MNN_PUBLIC struct MNNNet* MNNCreateNet(const char* path) {
if (NULL == path) {
MNN_PRINT("input path is NULL, failed to create net!\n");
return NULL;
}
// ...
}
对于内部入参,宜使用MNN_ASSERT避免问题代码的产生,如:
void copyFloats(const float* input, float* output, int size) {
MNN_ASSERT(NULL != input);
MNN_ASSERT(NULL != output);
for (int i = 0; i < size; ++i) {
output[i] = input[i];
}
}
禁止在没有注释适当理由的情况下,忽略错误入参,如:
void setUnitDimensions(const int* dims, int size) {
if (NULL == dims) return; // should not directly return without comments
for (int i = 0; i < size; ++i) {
dims[i] = 1;
}
}
对于所有非Op头文件:
示例:
/**
* @brief function description
* @param param param description
* @return return value description
*/
int example(int param) {
// ...
}
出于便于性能分析的理由,除引入的三方代码外,MNN代码需遵循:
出于控制库文件大小的理由,除引入的三方代码外,MNN代码需遵循:
出于跨平台编译的诉求,MNN代码需遵循: