Qt Creater中Clang-format的使用


起因在於習慣性的想格式化代碼,發現Qt Creater默認居然是沒有代碼格式化的,只有一個縮進,搞毛線啊!!!

 

搜索了下,倒是很容易就搜到了,Qt Creater中有個插件:beautifier,在 幫助-關於插件 中開啟了即可(需要重啟)。

可惜這只是一個接口,它的作用是調用格式化工具進行格式化。--這一點折騰了兩個小時才意識到!慘痛的教訓告訴我們,一定要看官方文檔,別老想着走捷徑!

 

按照官方的說法,它支持三種外部工具:Artistic Style、ClangFormat、Uncrustify 。並且都提供了下載地址。

這里僅以 ClangFormat 來說明。

 

ClangFormat 是LLVM的一個子功能,LLVM是類似GCC的東西。

所以,想用 ClangFormat ,就需要下載LLVM,根據上面的地址,搜索適合自己的版本即可。我這里是win64位的。

 

安裝的時候PATH選項無所謂,因為Qt Creater的beautifier Clang Format  選項中既可以根據PATH搜索,也可以自行指定路徑。

 

安裝好LLVM之后,就可以設置 Clang Format 選項了。

先配置路徑(如:C:\Program Files\LLVM\bin\clang-format.exe );

再選擇代碼樣式,默認有LLVM、Google、Chromium、Mozilla、WebKit、File,此外還可以自定義。

 

默認樣式,需要重點說一下File -- 因為其他的樣式都是給定的樣式,而 File 則不是。

File clang-format.exe -style=file 的意思,意味着 clang-format.exe 會去搜索樣式文件( *.clang-format 文件)。

需要注意的是,它的搜索路徑是當前文件所在的文件夾或者當前項目(不知道是否會繼續往上層搜索--至少,工作空間就沒驗證成功)。

這樣的話,它要求把 .clang-format 文件放在項目文件夾中,與我的習慣不符。

 

自定義樣式

所幸,還有一個選擇:Use customized style - add

如下

Value 部分內容如下

AccessModifierOffset: 0
AlignEscapedNewlinesLeft: false
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortFunctionsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackParameters: false
BreakBeforeBinaryOperators: false
BreakBeforeTernaryOperators: false
BreakConstructorInitializersBeforeComma: false
ColumnLimit: 128
BreakBeforeBraces: Attach
CommentPragmas: ''
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 0
ContinuationIndentWidth: 0
Cpp11BracedListStyle: false
DerivePointerBinding: false
IndentCaseLabels: true
IndentFunctionDeclarationAfterType: false
IndentWidth: 4
Language: Cpp
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
ObjCBlockIndentWidth: 4
PenaltyBreakBeforeFirstCallParameter: 100
PenaltyBreakComment: 100
PenaltyBreakFirstLessLess: 0
PenaltyBreakString: 100
PenaltyExcessCharacter: 1
PenaltyReturnTypeOnItsOwnLine: 20
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
TabWidth: 4
UseTab: Never

ps:上面這段配置是搜來的,忘了出處了~

 

使用

工具-Beautifier-ClangFormat 里面有兩個選項,分別是格式化當前文件格式化選定內容

 

但是,這樣使用很繁瑣,很難用。所以最好給它設置一個快捷鍵,我的是ALT+CTRL+L(intellij的快捷鍵)。

 

注意,ClangFormat 有個特殊的選項 Format entire file if no text was selected ,建議選中這個選項,這樣,只需要設置一個Format Selected Text 快捷鍵即可。

 

 

參考:

Beautifying Source Code

Clang-Format Style Options

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM