静态检查工具:提升代码质量的利器
创作时间:
作者:
@小白创作中心
静态检查工具:提升代码质量的利器
引用
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插件,就可以看到有问题的地方了。
参考链接
热门推荐
崇祯皇帝:末代君主与亡国之君的区别
潮声丨国漫崛起,浙江能造出下一个“哪吒”吗?
工程化益生菌制剂治疗溃疡性结肠炎取得新进展
市场结构分析:四种主要市场类型的特征与策略
浙江省人民医院发布10个AI智能体项目,推动医疗数字化转型
冬天吃什么可以提高免疫力?一份暖心又健康的饮食指南
你的终端安全吗?几个步骤教你防范网络安全风险
破防!35条线被砍!等到颈长!电鸡暴增!佛山公交"夹缝求生"
步进电机基础知识:类型、用途和工作原理
SolidWorks曲面建模技巧:快速创建复杂曲面的实用指南
以雇主为导向,以学生为中心 西安欧亚学院探索专业建设转型突围
为什么接种狂犬疫苗保定重要?
全球秩序与中美关系:阎学通“激辩”米尔斯海默
你以为正常,实则可能有害健康的8种东西
延边大学:民族教育的瑰宝
全网最全!葡萄牙居留许可申请指南
四川四日游攻略:探索美丽的自然与文化宝藏
文学与哲学的完美结合──浅谈苏轼的《前赤壁赋》
GSMA最新报告:详解中国5G发展的无限潜力
“西兰卡普”土家织锦闪耀非遗光彩 谭氏姐妹传承文化新篇章
《三角洲行动》S3赛季QJB201轻机枪改装攻略
世界第二高峰乔戈里峰:海拔8611米的"野蛮巨峰",攀登死亡率高达27%
日本艺术类大学申请全攻略
发病率上升至约18%的不孕不育,如何破解“孕育难”
佛教大愿心是什么意思?
锂电池如何正确进行充电?充电过程中如何确保电池安全?
中国银行获短信验证码攻击防护专利,提升金融安全防护能力
专家提醒:50岁后,这样休息比痴迷运动更助长寿
蔡骏最新悬疑《二十一天》:废墟之下的人性大考
机器学习撬动跨学科研究惊人力量