Как начать работу в clion
Quick start guide
0. Before you start
Is CLion a cross-platform IDE?
Yes, you can install and run CLion on Windows, macOS, and Linux.
See Install CLion for OS-specific instructions.
See CLion keyboard shortcuts for instructions on how to choose the right keymap for your operating system, and learn the most useful shortcuts.
What compilers and debuggers can I work with?
In CLion, you can use GCC-based compilers, Clang, Clang-cl, Visual Studio C++ compiler, as well as IAR compiler and custom-defined compiler. See Compilers for more information.
CLion supports debugging with GDB (either bundled or custom) on all platforms and with the bundled LLDB on macOS and Linux. Also, there is an LLDB-based debugger for the MSVC toolchain on Windows. Refer to the section on debugging below and to the page on Debugger options for details.
What build systems are supported? What are the project formats?
CLion fully integrates with the CMake build system: you can create, open, build and run/debug CMake projects seamlessly. CMake itself is bundled in CLion, so you don’t need to install it separately unless you decide to use a custom version.
Apart from CMake, CLion supports Makefile, compilation database, and Gradle projects. Creating new projects of these types in CLion is not supported currently.
Refer to Project Formats for details.
Do I need to install anything in advance?
On Windows, CLion requires a working environment. CLion bundles a version of the MinGW toolset for quick setup. You can use this bundled toolchain or switch to another MinGW installation, Cygwin, or Microsoft Visual C++. If you are working with WSL or Docker, you will need to install them as well.
On macOS, the required tools might be already installed. If not, update command line developer tools as described in Configuring CLion on macOS.
On Linux, compilers and make might also be pre-installed. Otherwise, in case of Debian/Ubuntu, install the build_essentials package and, if required, the llvm package to get Clang.
Are languages other that C++ supported as well?
Yes, CLion fully supports Python, Objective-C/C++, HTML (including HTML5), CSS, JavaScript, and XML. Support for these languages is implemented via the bundled plugins, which are enabled by default. See CLion features in different languages for more details.
You can install other plugins to get more languages supported in CLion (such as Rust, Swift, or Markdown). See Valuable language plugins.
1. Open/create a project
Open a local project
For CMake projects, use one of the following options:
Select File | Open and locate the project directory. This directory should contain a CMakeLists.txt file.
Checkout from a repository
Click Checkout from Version Control on the Welcome screen or select VCS | Checkout from Version Control from the main menu and choose your version control system.
Enter the credentials to access the storage and provide the path to the sources. CLion will clone the repository to a new CMake project.
Create a new CMake project
Select File | New Project from the main menu or click New Project on the Welcome screen.
Set the type of your project: C or C++, an executable or a library.
Note that STM32CubeMX and CUDA are also CMake-based project types.
Provide the root folder location and select the language standard.
CLion creates a new CMake project and fills in the top-level CMakeLists.txt :
The initial CMakeLists.txt file already contains several commands. Find their description and more information on working with CMake in our tutorial.
2. Take a look around
Project view shows your project files and directories. From here, you can manage project folders (mark them as sources, libraries, or excluded items), add new files, reload the project, and call for other actions such as Recompile.
Navigation bar helps you switch between the files’ tabs, and the Toolbar provides quick access to run/debug and VSC-related actions.
Right gutter shows the code analysis results with the overall file status indicator at the top.
Tool windows represent specific tools or tasks such as TODOs, CMake, terminal, or file structure.
Status bar shows various indicators for your project and the entire IDE: file encoding, line separator, memory usage, and others. Also, here you can find the resolve context switcher.
Any time you need to find an IDE action, press Ctrl+Shift+A or go to Help | Find Action and start typing the name of a command, setting, or even a UI element that you are looking for:
3. Customize your environment
Change the IDE appearance
The quickest way to switch between the IDE’s color schemes, code styles, keymaps, viewing modes, and look-and-feels (UI themes) is the Switch. pop-up. To invoke it, click View | Quick Switch Scheme or press Ctrl+` :
Tune the editor
Pages under the Editor node of the Settings / Preferences dialog help you adjust the editor’s behavior, from the most general settings (like Drag’n’Drop enabling and scroll configuration) to highlighting colors and code style options.
Adjust the keymap
There are also plugins that extend the list of available keymaps. For example, VS Code Keymap or Vim emulation (which includes the Vim keymap). Find more useful plugins for the CLion editor in Valuable non-bundled plugins.
4. Code with assistance
Auto-completion
Basic completion Ctrl+Space in CLion works as you type and gives a list of all available completions. To filter this list and see only the suggestions that match the expected type, use Smart completion Ctrl+Shift+Space :
Code generation
Even an empty class or a new C/C++ file contains boilerplate code, which CLion generates automatically. For example, when you add a new class, CLion creates a header with stub code and header guard already placed inside, and the corresponding source file that includes it.
To get the list of code generation options at any place in your code, press Alt+Insert to invoke the Generate menu:
These options can help you skip a lot of code writing. In addition to generating constructors/destructors, getters/setters, and various operators, you can quickly override and implement functions:
Intentions and quick-fixes
When you see a light bulb next to a symbol in your code, it means that CLion’s code analysis has found a potential problem or a possible change to be made:
Click the light bulb icon (or press Alt+Enter ) and choose the most suitable action or quick-fix:
Inspections
During on-the-fly code analysis, CLion highlights suspicious code and shows colored stripes in the right-hand gutter. You can hover the mouse over a stripe to view the problem description and click it to jump to the corresponding issue. The sign at the top of the gutter indicates the overall file status:
CLion detects not only compilation errors but also code inefficiencies like unused variables or dead code. Also, it integrates a customizable set of Clang-tidy checks.
You can also run inspections on demand for the whole project or a custom scope, and view the results in a separate window. For this, call Code | Inspect Code or use Code | Analyze Code | Run Inspection by Name Ctrl+Alt+Shift+I for a particular inspection.
From the results tool window, you can batch-apply quick fixes for several issues at a time. Click Fix partially in the description tab:
Refactorings
Refactorings help improve your code without adding new functionality, making it cleaner and easier to read and maintain. Use the Refactor section of the main menu or call Refactor This. Ctrl+Alt+Shift+T to get the list of refactorings available at the current location:
Rename Shift+F6 renames a symbol in all references;
Change Signature Ctrl+F6 adds, removes, or reorders function parameters, changes the return type, or updates the function name (affecting all usages);
Inline Ctrl+Alt+N /Extract inlines or extracts a function, typedef, variable, parameter, define, or constant;
Pull Members Up/Down ( Refactor | Pull Members Up / Push Members Down ) safely moves class members to the base or subclass.
5. Explore your code
Search everywhere
Find usages
To locate the usage of any code symbol, call Find Usages ( Alt+F7 or Edit | Find | Find Usages ). You can filter the results and jump back to the source code:
Navigate in the code structure
Switch between header and source file Ctrl+Alt+Home
Go to declaration/definition Ctrl+B Ctrl+Alt+B
Show file structure Alt+7
View type hierarchy Ctrl+H
View call hierarchy Ctrl+Alt+H
View import hierarchy Alt+Shift+H
For your code, CLion builds the hierarchies of types, call, imports, and functions. To view them, use the shortcuts given above or the commands in the Navigate menu. For example, type hierarchy helps you not only to navigate the code but also to discover what type relationships exist in the your codebase:
To explore the structure of the currently opened file, call View | Tool windows | Structure or press Alt+7 :
View pop-up documentation
Quick Documentation popup (available on mousehover or via the Ctrl+Q shortcut) helps you get more information on a symbol at caret without leaving the current context. Depending on the element you invoke it for, the popup shows:
function signature details,
code documentation (either regular or Doxygen comments),
inferred types for variables declared as auto :
formatted macro expansions :
Besides, you can instantly view the definition of a symbol at caret. Press Ctrl+Shift+I to invoke the Quick Definition popup:
6. Build and run
Run/Debug configurations
For each target in your project, CLion creates a run/debug configuration. It is a named setup which includes target, executable, arguments to pass to the program, and other options.
Edit Configurations dialog is accessible from the Run menu or the configuration switcher. Here you can manage the templates and add, delete, or edit your configurations.
For example, you can customize the steps to be taken Before launch : call external tools (including the remote ones), use CMake install, or even run another configuration.
Build actions
Build is included in many Run/Debug configuration templates as a default pre-launch step. However, you can also perform it separately by calling the desired action from the Build menu:
Notice the Recompile option that compiles a selected file without building the whole project.
Remote and embedded development
With CLion, you can also build and run/debug on remote machines including embedded targets. See the sections on Remote development and Embedded development.
7. Debug
CLion integrates with the GDB backend on all platforms (on Windows, the bundled GDB is available only for MinGW) and LLDB on macOS/Linux. You can switch to a custom version of GDB on all platforms. Also, CLion provides an LLDB-based debugger for MSVC on Windows.
Currently, the versions of the bundled debuggers are the following:
LLDB v 13.0.0 for macOS/Linux and 9.0.0 for Windows (MSVC)
GDB v 10.2 for macOS
GDB v 10.2 for Windows
GDB v 10.2 for Linux
Custom GDB v 7.8.x-11.1
IAR + Clion = дружба
Доброго здравия всем!
Карантин заставил меня проводить все свое время дома, в том числе и свободное время, и хотя дома есть куча дел, я умело спихнул их на сына, а сам решил наконец-то доизучать среду разработки Clion от JetBrains, тем более, что в релизе 2020.1 появилась поддержка IAR toolchain.
Все кому интересен пошаговый гайд и куча картинок велком.
Введение
В своей работе, для разработки программного обеспечения различных датчиков я использую C++ IAR Workbench компилятор. У него есть свои недостатки, например поздняя поддержка новых стандартов С++, у него есть несколько критичных багов, которые не позволяют создавать удобные конструкции и оптимальные вещи, но в целом я люблю его.
Всегда можно обратиться за поддержкой к IAR, попросить добавить какую-нибудь функциональность или сделать улучшения, а также, что немаловажно, компилятор имеет сертификат безопасности, а это означает, что я могу положиться на этот компилятор и во время сертификации ПО к нему не будет претензий.
Последние мои исследования (когда я вызвал внутренний assert у IAR компилятора и он выдал мне простыню из отладочной информации) говорят о том, что собственно этот компилятор сделан на основе Clang, что радует своей перспективой.
Но есть у IAR одна очень напрягающая вещь — это редактор. Он конечно развивается, в него добавился кривенький интелисенс, подсветка синтаксиса и другие фишки из прошлого, но в целом редактор можно описать фразой — «Powered by notepad».
Поэтому для работы и для студентов я искал что-то более современное, модное, молодежное, недорогое (а для студентов и подавно бесплатное).
Мой выбор пал на Clion от JetBrains.
Общая информация
Clion это среда для разработки на С/С++. Но я не буду описывать все его прелести, они довольно хорошо описаны в руководстве. Вместо этого, я покажу, как подключить IAR компилятор и как проводить отладку. Описать словами как все это настроить очень сложно, поэтому я просто буду вставлять картинки с небольшими пояснениями.
Как я уже сказал, в версии 2020.1 была добавлена поддержка IAR компилятора. Огромное спасибо за это Илье Моторному ака Elmot, потому что до версии 2020.1 работа с IAR была немного загадочной и не совсем понятной.
Он уже выкладывал здесь статью про свой плугин для поддержки разработки встроенного ПО с использованием ST Cube, а сейчас еще приложил руку и голову к поддержке IAR. Он также вкратце описал, как подружить Cube, IAR и Clion здесь.
Создание проекта
В основе работы Clion лежит система сборки CMAKE, и любой проект настраивается на основе файлов настроек дя CMAKE. Поэтому чтобы создать проект, достаточно просто указать папку где будут лежать ваши исходники. Можно создать проект уже из существующих исходников, в таком случае, Clion автоматически прошерстит указанную папку с исходниками, найдет все c и cpp файлы и добавит их в список (CMAKELIST) для сборки.
Но давайте создадим проект с нуля, чтобы было понятно, как оно настраивается руками. Для этого необходимо выбрать пункт меню File->NewProject
Нас интересует С++17 и тип выходного файла C++ Executable. На данном этапе ничего больше не надо.
Как я уже говорил, вся концепция сборки с Clion построена на использовании CMAKE, поэтому основным файлом сборки будет являться CMakeList.txt, содержащий настройки целей для сборки, списки подключаемых директорий, списки исходных файлов и многие другие вещи, необходимы для сборки.
На данный момент файл выглядит вот так:
Как видите в нем указана только минимально требуемая версия CMAKE +
Собственно имя проекта +
Стандарт С++, который мы выбрали при настройке+
И единственный исходный файл для сборки — main.cpp
Скоро мы добавим сюда немного настроек, а пока необходимо установить toolchain
Выбор и установка Toolchain
Clion в теории может работать с любым toolchain.
Toolchain — это набор инструментов для сборки программ из исходного кода. Обычно туда входит, стандартные библиотеки, компилятор, линковщик, ассемблер, отладчик и другие полезные вещи.
Но стандартно Clion поддерживает популярные тулчейны — MinGW, CygWin, Visual Studio
В списке нет IAR toolchain, но это не беда, можно установить любой стандартный, я пробовал с MinGW и Visual Studio с обоими работает прекрасно.
Поэтому для начала необходимо установить один из стандартных toolchain, которые поддерживает Clion.
C Visual Studio все понятно, нужно просто скачать установщик у Microsoft и установить С++ пакет (поставить галочку, потому что по умолчанию устанавливается только C#).
Поэтому сразу давайте разберемся с MinGW, скачать его можно отсюда http://www.mingw.org/.
Для полного понимания: нужен installer, его можно обнаружить справа на ссылках Popular или All time :
Далее запускаем MinGW и указываем путь, куда это все дело поставить:
Все это дело превосходно установится в течении минуты. Установка MinGW toolchain завершена. Перейдем теперь к настройкам.
Настройка
Сразу скажу, настроек в Clion немерено, я не будут рассказывать про все, цель статьи показать, как работать с IAR toolchain.
Выбираем из списка стандартных toolchain MinGW, ну или Visual Studio, если вы установили его. И ждём пока Clion сам определит местоположение компилятора, make утилиты, и отладчика.
Вообще ждать не обязательно, мы все равно это заменим своим 🙂
Теперь заменим все на нужный нам компилятор и отладчик. Для компиляции С и С++ файлов IAR использует тот же самый компилятор, поэтому просто в обоих случаях указываем один и тот же компилятор.
А вот отладчик нужно поменять либо на поставляемый (Bundled) с Clion, либо на отладчик из комплекта GNU ARM (можно скачать отсюда https://developer.arm.com/tools-and-software/open-source-software/developer-tools/gnu-toolchain/gnu-rm/downloads)
Самое простое использовать отладчик поставляемый с Clion:
Можно сразу переименовать ваш toolchain в IAR, чтобы отличать его от стандартного MinGW.
Утилиту make можно использовать из комплекта MinGW, но если очень хочется, то можно поменять её на любую другую, например, я использую clearmake, поставляемый с системой контроля версий ClearCase (не спрашивайте, почему — так исторически сложилось)
Вы также можете поменять make сборку на какую-нибудь другую, например на ninja, более подробно об этом можно прочитать здесь.
Базовая Настройка CMAKE
Перед тем как собирать проект, необходимо выполнить базовые настройки CMAKE, для различных вариантов сборок, например, Release или Debug. Создадим обе.
Для выбора типа сборки Debug или Release нужно использовать выпадающий список Build Type.
Точно также создаём еще один тип сборки Release.
После нажатия на кнопку Apply Clion должен будет пересобрать проект CMAKE, и если вы нигде не допустили ошибок, то после пересборки у вас должен появиться вот такой выбор в списке возможных сборок:
Все потому что мы не настроили ключи для компилятора и линковщика. Переходим к настройку CMake.
IAR выложил пример с настройками для CMake, он лежит здесь.
Все что я сделал, это добавил две ветки настроек для двух типов сборок Debug и Release.
Да еще поменял имя выходного файла на *.elf установив переменную set(CMAKE_EXECUTABLE_SUFFIX «.elf»)
Осталось добавить нашу настройку в CMakelist.txt:
Каждый раз когда вы меняете Cmakelist.txt или настройку toolchanin необходимо запускать пересборку Cmake проекта. Можно настроить, чтобы она делалась автоматически, но лучше просто руками нажимать на кнопку Reload Cmake, а вот для того, чтобы жестко пересобрать Cmake проект, лучше пойти в toolbox Cmake и выбрать там пункт Reset Cache and Reload Project
Теперь можно снова попробовать пересобрать проект, нажав на молоток. Если вы опять все сделали правильно — ваш простой проект должен собраться.
Настройка отладчика
Для отладки я буду использовать OpenOCD gdb сервер, но вы можете использовать Jlink gdb сервер или ST-Link gdb сервер.
Скачаем стабильную версию, на момент написания статьи это была версия 0.10.0: https://sourceforge.net/projects/openocd/files/openocd/0.10.0/ можно её собрать самому. Но если лень с этим возиться, то можно использовать неофициальную сборку под Windows: http://www.freddiechopin.info/en/download/category/4-openocd.
Итак, для настройки отладчика нужно сделать следующие шаги:
Убедитесь, что в настройках стоит gdb клиент из поставки File->Settings->Build,Execution,Deployment->Toolchains->Debugger: Bundled GDB
В шаблоне нет настроек и можно для каждого проекта использовать пустой шаблон и каждый раз его настраивать, а можно сразу настроить шаблон, чтобы в следующем проекте переиспользовать настройки.
Настроим сразу шаблон:
В опции Download executable поставим галочку, на Update Only — позволит загружать в микроконтроллер образ программы только в том случае, если были были какие-то изменения, в противном случае прошивки не будет.
OpenOCD по умолчанию работает по tcp протоколу, т.е. вы можете подключаться к серверу удалённо по IP адресу и порту по умолчанию 3333 (порт можно менять, но нам это не нужно). Так как запускаться OpenOCD будет на локальном компьютере, то и в опции target remote args нужно установить в значение tcp:127.0.0.1:3333
В опции GDB Server прописываем путь к OpenOCD, туда куда вы уже его скопировали на предыдущих шагах.
-c «reset_config none separate» — означает, что сброс производится через SWD без использования отдельной ножки сброса (а у меня как раз такой китайский отладчик).
-c «init» — запускает команду «init», которая запускает загрузочные OpenOCD скрипты под ваш целевой процессор
-c «reset halt»_ — выполняет немедленный сброс микроконтроллера после инициализации
В принципе все. Больше ничего не нужно. У вас должен получиться вот такой шаблон
Осталось на основе этого шаблона создать конфигурацию:
и выбираем наш Template. Переименовываем как-то по человечьи
И собственно теперь можно запускать на проверку, жмем на жука и смотрим, как все работает.
Завершающий этап
Для этого нам достаточно скопировать файл startup.cpp в папку проекта и добавить его в сборку.
Теперь наш проект готов и вы можете скачать его здесь: Постой проект с настройками для IAR
Для открытия в Clion достаточно зайти в меню File->Open и выбрать папку в которую вы его разархивировали.
Да остался один момент:
Убрать галочку Enable clangd server.
Заключение
В качестве заключения хотелось бы сказать, что работать в IAR IDE после Clion как то не очень хочется. Хотя для детальной отладки все таки придется использовать IAR, так как средства отладки там явно обширнее. С другой стороны к отладке я вообще редко обращаюсь, разве что проверить код студентов, когда он не работает.
Clion бесплатен для студентов и поэтому проблем с его установкой у них быть не должно, но и в принципе лицензия тоже не дорогая. Думаю, что студентам Clion серьезно облегчит жизнь и привнесет песчинку радости в их угрюмую жизнь, потому что сейчас больно смотреть на их муки написания кода. Да, что таить и на работе тоже.
А еще работать в Clion приятно, потому что все в одном. Например, эту статью я пишу тоже в Clion и сразу вижу её отображение.
А ведь есть еще куча всяких других плюшек, про которые я рассказывать не буду, они описаны на сайте JetBrains. Просто завершающий гифчик, показывающий скорость работы: