on style:在 Visual Studio Code (VS Code) 中配置 Clang-Format 格式化工具

在 Visual Studio Code (VS Code) 中配置 Clang-Format 格式化工具

Clang Format
https://clang.llvm.org/docs/ClangFormat.html

Clang-Format Style Options
https://clang.llvm.org/docs/ClangFormatStyleOptions.html

clang-format is located in clang/tools/clang-format and can be used to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.

1. Install clang-format on Ubuntu

  • Install clang-format by entering the following commands
  • yongqiang@yongqiang:~$ sudo apt updateyongqiang@yongqiang:~$ sudo apt-cache search clang-format # This command will list all the available versions.yongqiang@yongqiang:~$ sudo apt install clang-format -y
  • Display the version of this program
  • yongqiang@yongqiang:~$ clang-format --versionclang-format version 10.0.0-4ubuntu1yongqiang@yongqiang:~$yongqiang@yongqiang:~$ whereis clang-formatclang-format: /usr/bin/clang-format /usr/share/man/man1/clang-format.1.gzyongqiang@yongqiang:~$yongqiang@yongqiang:~$ which clang-format/usr/bin/clang-formatyongqiang@yongqiang:~$

    If clang-format is in your system path, you shouldn’t need to do anything.

    Note:
    Create a symbolic link for clang-format:

    sudo ln -s /usr/bin/clang-format-9.0 /usr/bin/clang-formatsudo ln -s /usr/bin/clang-format-6.0 /usr/bin/clang-format

    2. Create the .clang-format file

    An easy way to get a valid .clang-format file containing all configuration options of a certain predefined style is:

    clang-format -style=google -dump-config > .clang-formatclang-format -style=llvm -dump-config > .clang-format yongqiang@yongqiang:~/software$ clang-format -style=google -dump-config > .clang-formatyongqiang@yongqiang:~/software$ lltotal 16drwxr-xr-x 2 yongqiang yongqiang 4096 May 8 22:46 ./drwxr-xr-x 13 yongqiang yongqiang 4096 May 7 10:10 ../-rw-r--r-- 1 yongqiang yongqiang 4523 May 8 22:46 .clang-formatyongqiang@yongqiang:~/software$

    The style used for all options not specifically set in the configuration. Possible values:

    • LLVM: A style complying with the LLVM coding standards
    • Google: A style complying with Google’s C++ style guide
    • Chromium: A style complying with Chromium’s style guide
    • Mozilla :A style complying with Mozilla’s style guide
    • WebKit: A style complying with WebKit’s style guide
    • Microsoft: A style complying with Microsoft’s style guide
    • GNU: A style complying with the GNU coding standards

    3. Install the Clang-Format extension

    4. Configure ClangFormat options

    File -> Preferences -> Settings -> Remote [*] -> Clang-Format configuration

    Assume Filename: /home/yongqiang/software/.clang-format
    When reading from stdin, clang-format assumes this filename to look for a style config file (with -style=file) and to determine the language.

    Executable: /usr/bin/clang-format
    clang-format executable path

    Fallback Style: Google
    clang-format fallback style. (-fallback-style=value, value can be none, LLVM, Google, Chromium, Mozilla, WebKit)

    Style: file
    clang-format style.(-style=value, value can be file, LLVM, Google, Chromium, Mozilla, WebKit or json configure)

    5. Code formatting

    The C/C++ extension for Visual Studio Code supports source code formatting using clang-format which is included with the extension.

  • Format Document With…

  • Configure Default Formatter…

  • Clang-Format

  • You can format an entire file withFormat Document(Shift+Alt+F) or just the current selection withFormat Selection(Ctrl+K Ctrl+F) in right-click context menu. You can also configure auto-formatting with the following settings:

    • editor.formatOnSave - to format when you save your file.
    • editor.formatOnType - to format as you type (triggered on the ; character).

    By default, the clang-format style is set to “file” which means it looks for a .clang-format file inside your workspace. If the .clang-format file is found, formatting is applied according to the settings specified in the file. If no .clang-format file is found in your workspace, formatting is applied based on a default style specified in the C_Cpp.clang_format_fallbackStyle setting instead.

    6. Yongqiang Cheng

  • clang-format -style=google -dump-config > .clang-format
  • yongqiang@yongqiang:~/software$ clang-format -style=google -dump-config > .clang-formatyongqiang@yongqiang:~/software$ lltotal 16drwxr-xr-x 2 yongqiang yongqiang 4096 May 8 22:46 ./drwxr-xr-x 13 yongqiang yongqiang 4096 May 7 10:10 ../-rw-r--r-- 1 yongqiang yongqiang 4523 May 8 22:46 .clang-formatyongqiang@yongqiang:~/software$yongqiang@yongqiang:~/software$ cat ./.clang-format---Language: Cpp# BasedOnStyle: GoogleAccessModifierOffset: -1AlignAfterOpenBracket: AlignAlignConsecutiveMacros: falseAlignConsecutiveAssignments: falseAlignConsecutiveDeclarations: falseAlignEscapedNewlines: LeftAlignOperands: trueAlignTrailingComments: trueAllowAllArgumentsOnNextLine: trueAllowAllConstructorInitializersOnNextLine: trueAllowAllParametersOfDeclarationOnNextLine: trueAllowShortBlocksOnASingleLine: NeverAllowShortCaseLabelsOnASingleLine: falseAllowShortFunctionsOnASingleLine: AllAllowShortLambdasOnASingleLine: AllAllowShortIfStatementsOnASingleLine: WithoutElseAllowShortLoopsOnASingleLine: trueAlwaysBreakAfterDefinitionReturnType: NoneAlwaysBreakAfterReturnType: NoneAlwaysBreakBeforeMultilineStrings: trueAlwaysBreakTemplateDeclarations: YesBinPackArguments: trueBinPackParameters: trueBraceWrapping: 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: trueBreakBeforeBinaryOperators: NoneBreakBeforeBraces: AttachBreakBeforeInheritanceComma: falseBreakInheritanceList: BeforeColonBreakBeforeTernaryOperators: trueBreakConstructorInitializersBeforeComma: falseBreakConstructorInitializers: BeforeColonBreakAfterJavaFieldAnnotations: falseBreakStringLiterals: trueColumnLimit: 80CommentPragmas: '^ IWYU pragma:'CompactNamespaces: falseConstructorInitializerAllOnOneLineOrOnePerLine: trueConstructorInitializerIndentWidth: 4ContinuationIndentWidth: 4Cpp11BracedListStyle: trueDeriveLineEnding: trueDerivePointerAlignment: trueDisableFormat: falseExperimentalAutoDetectBinPacking: falseFixNamespaceComments: trueForEachMacros: - foreach - Q_FOREACH - BOOST_FOREACHIncludeBlocks: RegroupIncludeCategories: - Regex: '^<ext/.*\.h>' Priority: 2 SortPriority: 0 - Regex: '^<.*\.h>' Priority: 1 SortPriority: 0 - Regex: '^<.*' Priority: 2 SortPriority: 0 - Regex: '.*' Priority: 3 SortPriority: 0IncludeIsMainRegex: '([-_](test|unittest))?$'IncludeIsMainSourceRegex: ''IndentCaseLabels: trueIndentGotoLabels: trueIndentPPDirectives: NoneIndentWidth: 2IndentWrappedFunctionNames: falseJavaScriptQuotes: LeaveJavaScriptWrapImports: trueKeepEmptyLinesAtTheStartOfBlocks: falseMacroBlockBegin: ''MacroBlockEnd: ''MaxEmptyLinesToKeep: 1NamespaceIndentation: NoneObjCBinPackProtocolList: NeverObjCBlockIndentWidth: 2ObjCSpaceAfterProperty: falseObjCSpaceBeforeProtocolList: truePenaltyBreakAssignment: 2PenaltyBreakBeforeFirstCallParameter: 1PenaltyBreakComment: 300PenaltyBreakFirstLessLess: 120PenaltyBreakString: 1000PenaltyBreakTemplateDeclaration: 10PenaltyExcessCharacter: 1000000PenaltyReturnTypeOnItsOwnLine: 200PointerAlignment: LeftRawStringFormats: - 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: googleReflowComments: trueSortIncludes: trueSortUsingDeclarations: trueSpaceAfterCStyleCast: falseSpaceAfterLogicalNot: falseSpaceAfterTemplateKeyword: trueSpaceBeforeAssignmentOperators: trueSpaceBeforeCpp11BracedList: falseSpaceBeforeCtorInitializerColon: trueSpaceBeforeInheritanceColon: trueSpaceBeforeParens: ControlStatementsSpaceBeforeRangeBasedForLoopColon: trueSpaceInEmptyBlock: falseSpaceInEmptyParentheses: falseSpacesBeforeTrailingComments: 2SpacesInAngles: falseSpacesInConditionalStatement: falseSpacesInContainerLiterals: trueSpacesInCStyleCastParentheses: falseSpacesInParentheses: falseSpacesInSquareBrackets: falseSpaceBeforeSquareBrackets: falseStandard: AutoStatementMacros: - Q_UNUSED - QT_REQUIRE_VERSIONTabWidth: 8UseCRLF: falseUseTab: Never...yongqiang@yongqiang:~/software$
  • Yongqiang Cheng
    • ColumnLimit: 120

    The column limit.

    • IndentWidth: 4

    The number of columns to use for indentation.

    • TabWidth: 4

    The number of columns used for tab stops.

    References

    https://code.visualstudio.com/docs/cpp/cpp-ide
    https://clang.llvm.org/docs/ClangFormatStyleOptions.html
    https://learn.microsoft.com/en-us/visualstudio/ide/reference/options-text-editor-c-cpp-formatting

    相关推荐

    相关文章