Skip to content

Instantly share code, notes, and snippets.

@ishidur
Last active July 12, 2020 03:54
Show Gist options
  • Select an option

  • Save ishidur/c3f3101c61fe14478b3171d503c35a38 to your computer and use it in GitHub Desktop.

Select an option

Save ishidur/c3f3101c61fe14478b3171d503c35a38 to your computer and use it in GitHub Desktop.
clang-formatの設定 #windows

clang-formatを使ってC++のコードを自動で整形させる

なぜ自動整形する必要があるのか

  • コードを見やすくすることができる.
  • 書き方を統一することができる.
  • 毎回コミット前にformatする習慣をつけることで,無意味な変更がログに乗らなくなるのでlogを汚さずに済む

Setup

  1. LLVM Clangをインストールする
  2. http://releases.llvm.org/download.html より,Pre-Built BinariesのWindows(64-bit)版をダウンロードする.
  3. ダウンロードしたインストーラを実行し,インストールを行う.(LVVMをsystem PATHに追加すること)
  4. インストールが完了したら,コマンドプロンプトでclang --versionと入力して,正常にインストールされているかを確認する.
  5. formatを設定したいプロジェクトのフォルダ内に.clang-formatを作成する.これはformatのスタイルを定義するファイル.添付ファイルを参考にしてもよい.
  6. 以下のコマンドをコマンドプロンプト上で実行するとformatを行うことができる.
    clang-format -i  -style=file source.cpp
  7. また,毎回これを打つのが面倒であれば添付ファイルのようにシェルスクリプトを作成すると良い.

Advanced

余力があればgitのpre-commit hookを使ってコミットする前に自動的にformatが走るようにするのも良い

Ref

---
BasedOnStyle: 'Google'
AccessModifierOffset: -2
AlignEscapedNewlinesLeft: true
AlignConsecutiveAssignments: false
AlignEscapedNewlinesLeft: true
AlignTrailingComments: true
AllowShortBlocksOnASingleLine: true
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: 'Inline'
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: false
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: true
BinPackArguments: true
BinPackParameters: true
BreakBeforeBinaryOperators: 'None'
BreakBeforeBraces: 'Allman'
BreakConstructorInitializersBeforeComma: true
ColumnLimit: 80
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 2
ContinuationIndentWidth: 2
Cpp11BracedListStyle: true
DerivePointerBinding: true
IndentCaseLabels: true
IndentWidth: 2
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: true
MaxEmptyLinesToKeep: 1
NamespaceIndentation: 'None'
PointerAlignment: 'Left'
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: 'ControlStatements'
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
Standard: 'Cpp11'
TabWidth: 4
UseTab: 'Never'
IncludeCategories:
- Regex: '"stdafx.h"'
Priority: -1
#!/bin/bash
echo "Formatting Code..."
clang-format -i -style=file src/*.cpp
clang-format -i -style=file src/*.h
echo "done!"
exit 0
@ishidur

ishidur commented May 22, 2019

Copy link
Copy Markdown
Author

例にある.clang-formatでは,Includeの順番の並び替えで,必ずstdafx.hというヘッダを最初になるようにしたかったため,以下の記述を追加しています.不要であれば消してください.

IncludeCategories:
  - Regex:           '"stdafx.h"'
    Priority:        -1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment