Clang format qt creator windows

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Clang-format is a plug-in for formatting code that can be used to format C/C ++ / Java/JavaScript/Objective-C/Protobuf/C # code. In Qt Creator, the formatting code only supports very simple indentation correction. This blog mainly describes how to configure the clang-format plug-in on Qt Creator.

Open the Beautifier plug-in

Open theHelp -> About plug-ins -> Tick BeautifierAnd then restart Qt Creator.

Note that you must restart Qt Creator for the Beautifier plug-in to take effect.

Load the clang-format plug-in

First of all toLLVM download siteTo download the clang-format executable file. In this case, you need to choose the appropriate version according to your operating system and computer configuration. I downloaded the Windows 64-bit version.

After downloading the installation package, double-click install. Can customize the installation path, I was installed to D disk, here had better remember your installation path.

Open Qt Creator and clickTools -> Options ->Beautifier->Clang-format.

Click Browse, a Windows file window will pop up, findclang-format.exeDouble-click the file and Qt Creator will fill it in automaticallyclang-format.exeThe absolute path to the file. Of course, you can also choose to enter it manuallyclang-format.exeThe absolute path to the file.

And then clickUse customized style->Add.

In the new window that pops up, write the code formatting style you want. Refer to the SettingsClang-format Official document. My format is as follows:

{
BasedOnStyle: Google,
AccessModifierOffset: 2 -,
AlignAfterOpenBracket: Align,
AlignConsecutiveAssignments: false,
AlignConsecutiveDeclarations: false,
AlignEscapedNewlines: DontAlign,
AlignOperands: true,
AllowAllParametersOfDeclarationOnNextLine: true,
AllowShortBlocksOnASingleLine: true,
AllowShortCaseLabelsOnASingleLine: true,
AllowShortFunctionsOnASingleLine: All,
AllowShortIfStatementsOnASingleLine: false,
AllowShortLoopsOnASingleLine: false,
AlwaysBreakAfterDefinitionReturnType: None,
AlwaysBreakAfterReturnType: None,
AlwaysBreakBeforeMultilineStrings: false,
AlwaysBreakTemplateDeclarations: true,
AlwaysBreakAfterDefinitionReturnType: None,
AlwaysBreakAfterReturnType: None,
AlwaysBreakBeforeMultilineStrings: false,
AlwaysBreakTemplateDeclarations: true,
BinPackArguments: true,
BinPackParameters: true,
BreakBeforeBinaryOperators: None,
BreakBeforeBraces: Attach,
BreakBeforeTernaryOperators: false,
BreakConstructorInitializers: AfterColon,
BreakStringLiterals: true,
ColumnLimit: 120,
CommentPragmas: '^ IWYU pragma:',
CompactNamespaces: false,
ConstructorInitializerAllOnOneLineOrOnePerLine: false,
ConstructorInitializerIndentWidth: 4,
ContinuationIndentWidth: 4,
Cpp11BracedListStyle: true,
DerivePointerAlignment: false,
DisableFormat: false,
ExperimentalAutoDetectBinPacking: false,
FixNamespaceComments: true,
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ],
IncludeBlocks: Regroup,
IndentCaseLabels: true,
IndentPPDirectives:  AfterHash,
IndentWidth: 4,
IndentWrappedFunctionNames: true,
KeepEmptyLinesAtTheStartOfBlocks: false,
MacroBlockBegin: '',
MacroBlockEnd: '',
MaxEmptyLinesToKeep: 1,
NamespaceIndentation: All,
ObjCBlockIndentWidth: 4,
ObjCSpaceAfterProperty: false,
ObjCSpaceBeforeProtocolList: true,
PenaltyBreakBeforeFirstCallParameter: 19,
PenaltyBreakComment: 300,
PenaltyBreakFirstLessLess: 120,
PenaltyBreakString: 1000,
PenaltyExcessCharacter: 1000000,
PenaltyReturnTypeOnItsOwnLine: 60,
PointerAlignment: Left,
ReflowComments: true,
SortIncludes: true,
SpaceAfterCStyleCast: false,
SpaceAfterTemplateKeyword: true,
SpaceBeforeAssignmentOperators: true,
SpaceBeforeParens: ControlStatements,
SpaceInEmptyParentheses: false,
SpacesBeforeTrailingComments: 2,
SpacesInAngles: false,
SpacesInContainerLiterals: false,
SpacesInCStyleCastParentheses: false,
SpacesInParentheses: false,
SpacesInSquareBrackets: false,
TabWidth: 4,
UseTab: Never,
}
Copy the code

The Clang-format plug-in is installed. Hurry up and start a new one.hello worldGive it a try. Original code:

Click on theTools ->Beautifier->ClangFormat->Format Current File, you can format the code.

After formatting, the code format is as follows:

Set shortcut keys

Each formatting requires a lot of mouse clicks, some trouble. We can set a shortcut for the formatting code function. Click on theTools -> Options -> Environment -> Keyboard.

Search Clang and findFormatFileAt the bottomKey sequenceFill in the shortcut key you want. I set it toAlt+Shift+FJust click OK.

Using clang-format with QtCreator for consistent code style in a C++ project

Usually in projects with several people involved, a code style is written down. Like for example the one the Qt project has. This code style is usually checked manually in code reviews.

I have often seen ongoing debates about the style in reviews. Especially for new projects, or new members. Automating that task of the styling would make the life of new project members and reviewers a lot easier. Luckily such tools exist even for C++.

The currently best one is probably clang-format. One great feature is, that its configuration (code style) can be easily shared in the code repository. All that is needed is a .clang-format (or _clang-format) file containing the configuration. One example of a .clang-format configuration that matches the Qt style very well (as Qt might use it mandatory in the future) can be found here. Many IDEs and editors have support for that tool. QtCreator as well. So it’s easy for new/all members of a project to comply the coding style. And here is a short tutorial on how to configure QtCreator to use clang-format:

First you need to have clang-format installed. For Windows, it is included in the clang package. Linux distributions usually have packages included already. MacOS users can for example use brew to install it.

Next is to create a .clang-format file in the root directory of your project. Configuration options can be found here. There is even a (very slow) tool to generate a configuration out of your existing code.

In QtCreator the beautifier plugin needs to be enabled in “Help -> About Plugins…” 

Перейти к содержимому

Устанавливаем clang-format на Ubuntu из основного репозитория:

sudo apt install clang-format

Или свежую версию из репозитория LLVM:

wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add -
sudo apt update
sudo apt install clang-format-12

Запускаем Qt Creator. Идем «Справка -> О модулях…«. Ставим галочку на Beautifier.

Идем в «Инструменты -> Параметры…«.

Можно включить форматирование при сохранении файла.

На вкладке Clang Format указываем путь к clang-format.

Можно использовать стандартный стиль, а можно создать собственный.

Стиль сохраняется в домашнюю папку по следующему пути:

$HOME/.config/QtProject/qtcreator/beautifier/clangformat/my_style/.clang-format

Допустим у вас уже есть файл .clang-format, который хранится в репозитории вашего проекта. Тогда можно создать символическую ссылку на него:

rm $HOME/.config/QtProject/qtcreator/beautifier/clangformat/my_style/.clang-format

ln -s my_project/.clang-format $HOME/.config/QtProject/qtcreator/beautifier/clangformat/my_style/.clang-format

Можно настроить горячие клавиши для форматирования:

Clang format and code beautifier for Qt Creator

Different developers use different styles with different IDE (i.e some people use space, some use tab) which may cause lots of changes in your git repository. One solution to this is to use some standard code formatting and beautifier. clang is a great tool for this purpose and can be easily integrated with git hooks and IDE.
First, install it by:

sudo aptget install clangformat

now, if you have a file like this:

after running, the following:

clangformat style=WebKit i main.cpp

now you can use it like:

Available styles are LLVM, Google, Chromium, Mozilla, WebKit.

You can config clang for Qt Creator:

go to Tools>Option then:

Apply the formatting to the entire project

Apply the following script:

find foo/bar/ iname *.h o iname *.cpp | xargs clangformat i

alternatively:

find . regex ‘.*\.\(cpp\|hpp\|cc\|cxx\) exec clangformat style=file i {} \;

On Windows machines:

GetChildItem Path . Directory Recurse |

foreach {

cd $_.FullName

echo $_.FullName

&clangformat i style=file *.cpp *.hpp *.h

}

Turing off clang formatting

You can turn off the formatting by the following:

// clang-format off

void unformatted_code

// clang-format on

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Автозапуск программы в трее windows 10
  • Windows crlf что это
  • How to reboot windows server
  • Как установить unarc dll для windows 10 x64
  • Прекращена работа программы windows update