- Qt Documentation
- Contents
- Running Clang Tools
- Configuring Clang Tools
- Selecting Clazy Check Levels
- Creating Clang-Tidy Configuration Files
- Как использовать Clang kit с Qt Creator на Windows?
- Решение
- Qt Creator Clang Code Model
- Contents
- Debugging
- Internal command line
- Related Environment Variables
- Build related
- Run time related
- Libclang
- Builds
- Minimal libclang installation that Qt Creator can use
Qt Documentation
Contents
Qt Creator integrates the following Clang tools for finding problems in C, C++, and Objective-C source code by using static analysis:
- Clang-Tidy, which provides diagnostics and fixes for typical programming errors, such as style violations or interface misuse.
- Clazy, which helps Clang understand Qt semantics. It displays Qt related compiler warnings, ranging from unnecessary memory allocation to misuse of API and provides refactoring actions for fixing some of the issues.
Note: The Clang static analyzer checks are a part of Clang-Tidy. To use the checks you must create a custom configuration for the Clang tools and enable them for Clang-Tidy.
Clang tools are delivered and installed with Qt Creator, and therefore you do not need to set them up separately.
In addition to running the tools to collect diagnostics, you can select to load diagnostics from YAML files that you exported using the -export fixes option.
Running Clang Tools
To run the Clang tools to analyze the currently open file:
- Select the
(Analyze File) button on the editor toolbar.
- Select Tools >C++ >Analyze Current File.
To run the Clang tools to analyze an open project:
- Select Analyze >Clang-Tidy and Clazy.
The found issues are displayed in the Clang-Tidy and Clazy view:
Note: If you select Debug in the mode selector to open the Debug mode and then select Clang-Tidy and Clazy, you must select the (Start) button to open the Files to Analyze dialog.
Double-click an issue to move to the location where the issue appears in the code editor.
If a fixit exists for an issue, you can select the check box next to the issue to schedule it for fixing. Select the Select Fixits check box to select all fixits. You can see the status of an issue by hovering the mouse pointer over the icon next to the check box.
To see more information about an issue that is marked with the icon, hover the mouse pointer over the line.
Select the button to customize Clang diagnostics for the current project.
To restore the global settings, select Restore Global Settings. To view and modify the global settings, select Open Global Settings. To open the Clang static analyzer, select Go to Analyzer.
Configuring Clang Tools
To configure Clang diagnostics globally for Clang tools:
In the Clang-Tidy Checks tab, select Select Checks to select the checks to perform.
For more information about the available checkers, see Clang Static Analyzer documentation.
To suppress diagnostics, select Suppress This Diagnostic in the context menu. To view the suppression list for a project and to remove diagnostics from it, select Projects > Project Settings > Clang Tools.
Selecting Clazy Check Levels
The Clazy checks are divided into levels from 0 to 3. The checks at level 0 are very stable and provide hardly any false positives, while the checks at level 3 can be considered experimental. You can select the checks to perform at each level. To include the checks from the lower levels automatically, select the Enable lower levels automatically check box.
Creating Clang-Tidy Configuration Files
Clang-Tidy reads the configuration for each source file from a .clang-tidy file located in the closest parent directory of the source file. If any configuration options have a corresponding command-line option, the command-line option takes precedence. The effective configuration can be inspected using -dump-config .
Qt Creator creates the configuration for you based on the checks you select. To store the checks in file format, you can create a .clang-tidy file, as follows:
- Select Edit Checks as String and copy the contents of the field.
- Pipe the output of clang-tidy -dump-config into a file named .clang-tidy . For example: clang-tidy -checks=-*,bugprone-*,cppcoreguidelines-avoid-* -dump-config > .clang-tidy
- Move the .clang-tidy file to the parent directory of the sources.
To add more checks using Qt Creator later on, copy the checks from your .clang-tidy file into the Edit Checks as String field, select additional checks, and copy-paste the contents of the field to the .clang-tidy file.
В© 2021 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.
Как использовать Clang kit с Qt Creator на Windows?
(этот вопрос похож на этот но не то же самое)
Я использую QtCreator на платформе Windows, обычно с vc toolchain.
иногда с MinGW-W64, поэтому сейчас я хотел бы попробовать clang по некоторым причинам.
в отличие от поста выше — я не использую библиотеку Qt, просто qtcreator в качестве IDE, поэтому я полагаю, что мне не нужно пересобирать ее и QtCreator для использования набора clang, это правильно?
Есть несколько вопросов по этому поводу:
- Дистрибутив CLang не содержит платформу или даже библиотеку времени выполнения c / c ++. Должен ли я использовать ее из vc kit? или / и MinGW Runtime? как переключаться между?
- Исправьте мое понимание, пожалуйста, если это не так — для платформы Win clang имеет два варианта использования: 1) обычное использование — clang.exe, как и на любой другой платформе 2) clang-cl.exe — дополнительный слой, который «выглядит» как cl. exe, и просто анализирует ключи командной строки cl и вызывает обычный clang.
- насколько я понимаю, нет платформы LLDB для Windows, могу ли я использовать GDB или CDB, зависит от используемой среды выполнения lib и двоичного формата исполняемого файла?
и напоследок — как все это настроить в qtcreator?
Решение
Следующие шаги применимы только к MSYS2 64-битной установке QT Creator 4.5.1 (инструкции по установке Вот ), где у вас также установлены MinGW-w64 и mingw32-make на MSYS2; и вы создаете не-QT C или C ++ приложение.
В этих инструкциях используется QMake, потому что QBS не поддерживает MSL2 clang. Ну, QMake также не поддерживает его, но я выяснил, как добавить поддержку QMake, и я не понял QBS.
Существует поддержка QMake для MSVC-clang, но он выводит make-файлы MSVC, поэтому вы не можете собрать его с помощью MSYS2 make. Так что это не относится к нам.
- Установите Clang с pacman , я использовал pacman -Ss mingw-w64-x86_64-clang Ваш вкус может отличаться.
- Добавить поддержку для clang в QMake:
- В оболочке MSYS2 зайдите в /msys64/mingw64/share/qt5/mkspecs/
- Делать cp -a win32-g++ win32-clang-msys
- редактировать win32-clang-msys/qmake.conf и изменить gcc в clang , а также g++ в clang++ (2 места каждый)
- В том же файле вынь -fno-keep-inline-dllexport -mthreads которые не поддерживаются clang.
- В QT Creator установите новый комплект:
- Перейти к управлению комплектами.
- Добавьте пользовательский компилятор для C и перейдите к установленному пути ( /mingw64/bin/clang.exe под вашим MSYS2 установить).
- Добавьте пользовательский компилятор для C ++ как clang++.exe в том же месте)
- Добавить ручной комплект под названием Clang и установить эти два компилятора в качестве его компиляторов.
- В конфиге ручного комплекта установите «Qt mkspec» как win32-clang-msys
- Установите «QT Version» на что-то. Несмотря на то, что я использую не-QT проект, IDE не любит использовать комплект, если для «Qt version» установлено значение None.
Теперь вы можете попытаться построить свой проект с Clang обвес и QMake.
Я изначально пытался с QBS и сборка не удалась из-за эта ошибка . Но команды сборки будут успешными, если я скопирую их и вырежу фальшивку -target переключатель. Так что для пользователей QBS, я полагаю, вам следует переключиться на QMake, пока они не исправят эту ошибку.
Поиск проблемы: Я иногда получаю ошибку Project ERROR: failed to parse default search paths from compiler output , Это проблема с отсутствием поддержки QMake для Clang. Ошибка, как правило, не происходит, если я построил в подкаталоге .pro файл, но это произошло, если я встроил в одноуровневую директорию.
В качестве обходного пути: вернитесь в win32-clang-msys/qmake.conf , Поменяй первый clang вернуться к g++ , Затем «Запустите Qmake» (от создателя QT или командной строки), затем верните его обратно. При первом запуске QMake записывает файл .qmake.stash и тогда не нужно генерировать его снова. Содержимое этого файла было поддельным для меня, но здание все равно работало.
Неопределенные ссылки: Я обнаружил, что связь с -static произвел кучу неопределенных ссылок на __imp__cxa_ имена. Не уверен, что проблема здесь, но, возможно, связана с ошибкой генерации .qmake.stash , Я предполагаю, что разработчикам Qt нужно будет официально добавить поддержку не-MSVC Clang в QMake.
Несколько определений: Компоновщик CLang дал несколько определений для встроенных функций DLLexport. Я еще не нашел обходного пути для этого; G ++ имеет -fno-keep-inline-dllexport чтобы избежать этой проблемы, но CLang 5 не поддерживает этот флаг.
Qt Creator Clang Code Model
Contents
Debugging
With the following invocation debugging output will be generated:
Windows (start DebugView in advance to see the output):
The debugging output contains among others:
- The IPC messages send/received
- Output of libclang while parsing
Internal command line
The debugging output from above will contain all the command line options that are passed on to libclang, which is enough for most cases.
However, to see also the resulting internal command line of libclang run:
- Restart Qt Creator with QTC_CLANG_NO_DIAGNOSTIC_CHECK=1 (>= Qt Creator 4.5)
- Switch to projects mode and there to the «Clang Code Model»
- Copy some warning configuration by clicking on «Copy. «, give it a name like «Debug»
- Replace all the options from the copied configuration with «-###»
- Close and re-open the editor document — the new debugging output will contain also the internal command line
Note that libclang/clangbackend will crash afterwards, so do not forget to switch back to a sane warning configuration.
Related Environment Variables
Build related
- QTC_ENABLE_CLANG_LIBTOOLING — Build against Clang’s C++ libs; the ClangFormat and ClangRefactoring plugin and dependencies will be build.
Run time related
- LIBCLANG_TIMING — Timings from libclang for parse / reparse / preamble generation / completion.
- QTC_CLANG_ENABLE_STACKTRACES — For debugging. Enables the clang stack trace printer on a crash. Might deadlock clangbackend.
- QTC_CLANG_NO_DIAGNOSTIC_CHECK — Avoid validation of warning configuration (>= Qt Creator 4.5)
- QTC_CLANG_NO_SUPPORTIVE_TRANSLATIONUNIT — Use only one translation unit per document.
- QTC_CLANG_NO_ALIVE_TIMER — Simplifies debugging in certain cases.
- QTC_CLANG_FORCE_VERBOSE_ALIVE — Simplifies debugging in certain cases.
Libclang
libclang is used inside clangbackend to provide code model features
Builds
libclang is built with the same compilers as Qt Creator («Clang 7.0 (Apple)» for macOS, and GCC 5.3 from RHEL (which turns on old ABI compatibility with _GLIBCXX_USE_CXX11_ABI=0 by default) on Linux)
Currently libclang is built with optimized MinGW compiler for all Qt Creator versions. More information about Windows builds: Build libclang on Windows
Minimal libclang installation that Qt Creator can use
The following targets are sufficient for this: