问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

静态检查工具:提升代码质量的利器

创作时间:
作者:
@小白创作中心

静态检查工具:提升代码质量的利器

引用
CSDN
1.
https://blog.csdn.net/lovely_yoshino/article/details/137224676

静态检查是软件开发过程中的一个重要环节,它在代码执行之前分析源代码或编译后的代码,以识别潜在的错误、代码规范违规、安全漏洞等问题。静态检查的好处包括提高代码质量、减少bug、增强安全性、提升开发效率等。它能够帮助开发者在早期发现问题,减少后期调试的工作量,以及降低维护成本。我们很多常见的编译器无法识别的问题都可以通过静态检查识别可能存在的问题。

1. 静态检查工具的重要性

通过静态分析可以发现的错误类型包括:

  • 未定义的行为
  • 使用危险的代码模式
  • 编码风格

静态分析应作为质量保证的补充。它不能取代任何精心设计、测试、动态分析或模糊测试。

2. cppcheck使用指南

Cppcheck 是 C/C++ 代码的静态分析工具。它提供独特的代码分析来检测错误,并专注于检测未定义的行为和危险的编码结构,即使它具有非标准语法(在嵌入式项目中很常见)。使用起来还是比较轻松地,即在vscode中安装这个扩展即可。最新的版本自带了一个 cpp checker 的库,因此无需额外下载,可以直接使用。

在VSCode中配置cppcheck

在用户设置中追加下面的代码:

"cpp-check-lint.cpplint.--enable": false,  //google C++ 代码风格检查
"cpp-check-lint.cppcheck.--language=": "c",  //使用c语言进行检查
"cpp-check-lint.cppcheck.--inline-suppr": false,  //取消内联
"cpp-check-lint.cppcheck.--onsave": true,  //在文件保存时立刻检查该文件
"cpp-check-lint.cppcheck.--enable=": "style",  //输出信息等级,可选为all, warning, style, performance, portability, information, unusedFunction, missingInclide

在需要检查一个文件时,可以右键可以进行检查,然后就可以在终端中看到对应的报错和警告了。

3. 代码格式规范化

这里可以用clang-format来规范化,首先需要安装版本

sudo apt install clang-format

然后可以查看clang的版本号,确保安装成功

clang-format --version

然后新建一个.clang-format文件,并放在对应repo的根目录下

Language:        Cpp
BasedOnStyle:  Google
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveMacros: false
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Left
AlignOperands:   true
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: false
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: false
BinPackParameters: false
BraceWrapping:
  AfterCaseLabel:  false
  AfterClass:      false
  AfterControlStatement: false
  AfterEnum:       false
  AfterFunction:   false
  AfterNamespace:  false
  AfterObjCDeclaration: false
  AfterStruct:     false
  AfterUnion:      false
  AfterExternBlock: false
  BeforeCatch:     false
  BeforeElse:      false
  IndentBraces:    false
  SplitEmptyFunction: true
  SplitEmptyRecord: true
  SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit:     80
CommentPragmas:  '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DeriveLineEnding: true
DerivePointerAlignment: false
DisableFormat:   false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks:   Regroup
IncludeCategories:
- Regex:           '^<ext/.*\.h>'
    Priority:        2
    SortPriority:    0
- Regex:           '^<.*\.h>'
    Priority:        1
    SortPriority:    0
- Regex:           '^<.*'
    Priority:        2
    SortPriority:    0
- Regex:           '.*'
    Priority:        3
    SortPriority:    0
IncludeIsMainRegex: '([-_](test|unittest))?$'
IncludeIsMainSourceRegex: ''
IndentCaseLabels: true
IndentGotoLabels: true
IndentPPDirectives: None
IndentWidth:     4
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd:   ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Never
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Right
RawStringFormats:
- Language:        Cpp
    Delimiters:
- cc
- CC
- cpp
- Cpp
- CPP
- 'c++'
- 'C++'
    CanonicalDelimiter: ''
    BasedOnStyle:    google
- Language:        TextProto
    Delimiters:
- pb
- PB
- proto
- PROTO
    EnclosingFunctions:
- EqualsProto
- EquivToProto
- PARSE_PARTIAL_TEXT_PROTO
- PARSE_TEST_PROTO
- PARSE_TEXT_PROTO
- ParseTextOrDie
- ParseTextProtoOrDie
    CanonicalDelimiter: ''
    BasedOnStyle:    google
ReflowComments:  true
SortIncludes:    true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: false
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles:  false
SpacesInConditionalStatement: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
Standard:        Auto
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth:        4
UseCRLF:         false
UseTab:          Never

然后可以在VScode中安装对应的插件

在VSCode中配置clang-format

在setting.json中输入下面的代码,以指定格式

"C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: Google, IndentWidth: 4, TabWidth: 4, AccessModifierOffset: -4, BinPackArguments: false, BinPackParameters: false, AllowAllArgumentsOnNextLine: false, AllowAllParametersOfDeclarationOnNextLine: false, ColumnLimit: 100 }",
"C_Cpp.clang_format_style": "{ BasedOnStyle: Google, IndentWidth: 4, TabWidth: 4, AccessModifierOffset: -4, BinPackArguments: false, BinPackParameters: false, AllowAllArgumentsOnNextLine: false, AllowAllParametersOfDeclarationOnNextLine: false, ColumnLimit: 100 }",

4. 其他静态检查工具

除了cppcheck,还可以使用C/C++ Advanced Lint插件。安装步骤如下:

sudo apt-get install llvm
sudo apt-get install clang
sudo apt-get install cppcheck

然后安装C/C++ Advanced Lint插件,就可以看到有问题的地方了。

参考链接

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号