Quick start guide
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
Use one of the following options:
Select File | Open and locate the project directory.
This directory should contain a CMakeLists.txt file.
Select File | Open and point CLion to the top-level CMakeLists.txt file, then click Open as Project .
Select File | Open and locate the CMakeCache.txt file, then click Open as Project .
Select File | Open from the main menu.
Point CLion to the folder containing the top-level Makefile or to Makefile itself (in this case, click Open as Project on the next step).
Select File | Open from the main menu.
Point CLion to the folder containing compile_commands.json or to the compile_commands.json itself (in this case, click Open as Project on the next step).
Select File | Open from the main menu.
Point CLion to the folder containing build.gradle or to the build.gradle file itself (in this case, click Open as Project on the next step).
Clone a repository
Click Get from VCS on the Welcome screen or select Git (or your VCS) | Clone .
Enter the credentials to access the storage and provide the path to the sources.
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

Find a detailed description of the UI elements in User interface.

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+` :
To explore all the customizable options, go to the dedicated pages in Settings Ctrl+Alt+S .
Tune the editor
Pages under the Editor node of the Settings 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.

Code styles are configurable for each language separately in the pages under the Editor | Code Style node. For C/C++ , you can set one of the predefined code styles or provide your own, and configure the desired naming convention including the header guard template:
Adjust the keymap
In CLion, almost every action possible in the IDE is mapped to a keyboard shortcut. To view the default mapping, call Help | Keyboard Shortcuts PDF .
You can customize the shortcuts in Settings| Keymap . Use one of the predefined keymaps (Visual Studio, Emacs, Eclipse, NetBeans, Xcode, and others) and tune it as required, or create your own keymap from scratch.
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

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 :

Completion, along with other code insight features, is available for CMake code as well. See Code assistance in CMakeLists.txt.
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.
One of the most useful code generation features is create from usage . It helps you focus on the ideas as they come up and takes care of the routine.

For example, when you call a function that is not yet implemented, there is no need to break the flow: press Alt+Enter to generate stub code that you can come back to later. Create from usage works for variables and classes as well:
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:

Live templates are the tool to generate entire code constructs. Find the list of ready-to-use templates in Settings | Editor | Live Templates . To paste a template in your code, call Code | Insert Live Template or press Ctrl+J , for example:

To quickly surround your code with loops and conditional statements like if , while , for , #ifdef , call Code | Surround With or press Ctrl+Alt+T :
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:
indicates an error and lets you choose a quick fix for it,
indicates that one or several intention actions are available.

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.
To enable or disable inspections, configure their severity levels (whether an inspection should raise an error or just be shown as a warning) and set the scopes, go to Settings | Editor | Inspections .
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:

See the Static code analysis section for more information.
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

To search for anything in CLion, be it an item in your codebase, action, or UI element, press Shift twice and start typing what you are looking for in the Search Everywhere dialog. Use the filter menu to narrow your search:
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 :
Also, use the left gutter icons to quickly jump to a declaration/definition or navigate through the class hierarchy (/, /).
View pop-up documentation
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 single file
If you have only one or two files to compile and run, there is no need for you to get into project models: your files can be compiled and run/debug without it.
In the editor, click the left gutter icon next to your program’s entry point and select the action:
See Run/debug single file for more information.
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.
Run/Debug configurations are generated from templates , such as CMake Application, Google Test, Remote GDB Debug, and so on. The templates are customizable: when you edit a template parameter, you change the default settings of all configurations that will be created from this template later.
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.

To launch your program, select the desired configuration and use commands from the Run menu or press Shift+F10 . Alternatively, invoke the Run Anything dialog by pressing Ctrl twice and start typing the configuration name:
Hold down Shift to switch to Debug Anything.
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 15.0.1 for macOS/Linux and 9.0.0 for Windows (MSVC)
GDB v 12.1 for macOS
GDB v 12.1 for Windows
GDB v 12.1 for Linux
Custom GDB v 7.8.x-12.1
To start a debug session, select the desired configuration and press Shift+F9 or click . You can set breakpoints by clicking the gutter next to a code line. To follow through the execution process, use debugger’s stepping actions
.
In the Variables tab of the debugger tool window, you can explore the values and change them without interrupting your debug session. To evaluate an expression, click or press Alt+F8 . CLion also shows the current variables’ values right in the editor, and in case you enable hex view, it is shown inlined as well:
Getting Started with CLion and CMake
Hello, this is a simple post on getting started with CLion and CMake. I am taking a module in school which uses these tools. I thought i would share some findings i discovered along the way as i tried to set up my PC.
(1) CLion
CLion is an IDE for cross-platform development in C++ language. We can think of Clion to be similar to intellij in Java or Webstorm for Javascript programming.
Extra CLion Configurations for Windows
Tutorial: Configure CLion on Windows — Help | CLion
On Windows, configuring CLion requires setting up the environment: Cygwin, MinGW, WSL, or Microsoft Visual C++. You can…
If your computer is on Windows, then you need to perform an additional configuration step on CLion to set up the environment: Cygwin, MinGW, WSL or Microsoft Visual C++ for adding the C++ Compilor.
Here, i choose to use Visual Studio (Purple Logo).
Previously, i selected MinGW but then the code had some problems. Hence, i switched to the Visual Studio instead.
Note: If you skip this section and you have a windows computer, then you might face issues running the next step with CMake. Screenshots below are the error messages i faced in CLion (this is after i started a new project file in CLion and tried to run CMakeLists.txt file in CLion) before installing Visual Studio 🙁
(2) CMake
CMake is a tool used by Clion for development. CMake is used to control the software compilation process using (simple platform and compiler independent) configuration files, and generate native makefiles and workspaces that can be used in the compiler environment of your choice.
CMake uses scripts called CMakeLists to generate build files (makefiles) for a specific environment.
(3) Working with CMake in CLion
Quick CMake tutorial — Help | CLion
This tutorial will guide you through the process of creating and developing a simple CMake project. Step by step, we…
Check out the tutorial in the link above for a step by step tutorial on setting up a CMake project. The content in this section is referenced from the link.
When you create a new CMake project in CLion, a CMakeLists.txt file is automatically generated under the project root. Depending on the complexity of your project, you might have a CMakeLists.txt file for each folder. An example of a CMakeLists.txt file is as shown below.
Executable Target
The last line, executable target, is an executable to be built using a CMake script.
In the above image, our test project has only one build target, cmake_testapp. Upon the first project loading, CLion automatically adds a Run/Debug configuration associated with this target:
Click Edit Configurations in the switcher or select Run | Edit Configurations from the main menu to view the details. The target name and the executable name were taken directly from the CMakeLists.txt:
Notice the Before launch area of this dialog: Build is set as a before launch step by default. So we can use this configuration not only to debug or run our target but also to perform the build.
If we want to add another file, titled calc.cpp, we need to update the CMakeLists.txt file.
Library Targets
Previously, to add executables target, we used add_executable(). If we want to add library targets, we need another command add_library(). As an example, let’s create a static library from the calc.cpp source file:
As well as for executables, CLion adds a Run/Debug configuration for the library target after reloading the project:
However, this is a non-executable configuration, so if we attempt to run or debug it, we will get the Executable not specified error message.
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
В появившемся окне указываем путь к проекту, выбираем язык, тип выходного файла, версию языка и жмем кнопку Create . Конечно все это потом можно руками поменять в настройках CMAKE.
Нас интересует С++17 и тип выходного файла C++ Executable. На данном этапе ничего больше не надо.

Если вы заметили в настройках проектах уже сть опция Embedded->STM32CubeMX , она позволяет вам создать файл .ioc, в который затем можно добавить настройки из STM32CubeIDE. А поскольку Clion может работать с .ioc файлом, то все изменения в нем экспортируется в проект Clion.
Но это не наш вариант, мы хотим работать с IAR компилятором и микроконтроллерами по брутальному без всяких там Cubов. Итак, мы создали пустой проект, который содержит только один исходных файл main.cpp .

Как я уже говорил, вся концепция сборки с 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 и указываем путь, куда это все дело поставить:

После копирования файлов, жмем Continue, запуститься Менеджер Инсталляции. Все что нам нужно это GNU C++ Compiler (собственно и он то не нужен, но нужно, чтобы, что-то было установлено) и Базовая инсталляция. Выбрали — жмем ApplyChanges .

Все это дело превосходно установится в течении минуты. Установка MinGW toolchain завершена. Перейдем теперь к настройкам.
Настройка
Сразу скажу, настроек в Clion немерено, я не будут рассказывать про все, цель статьи показать, как работать с IAR toolchain.
Итак, для начала идем в настройку Clion — File->Settings->Build, Execution, Deployment -> 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. Создадим обе.
Для этого идем в File->Settings->Build, Executiion, Deployment -> CMake

И жмем на «+» плюсик

Автоматически у вас создастся конфигурация сборки для Debug. Здесь можно добавить кое какие опции для CMake, поменять папку для сборки, и добавить опции для make или другого сборщика (Build Options). По умолчанию, стоит ключ -j 16( у вас может быть и больше), что означает задействовать все 16 ядер для параллельной компиляции модулей. Такой параллелизм хорошо работает, кода весь код лежит на локальной машине, но если он лежит где-нибудь в сети или удалённой системе контроля версии (моя история) и этот доступ осуществляется медленно, через VPN, то лучше поставить компиляцию на одно ядро.
Для выбора типа сборки Debug или Release нужно использовать выпадающий список Build Type.
Точно также создаём еще один тип сборки Release.
После нажатия на кнопку Apply Clion должен будет пересобрать проект CMAKE, и если вы нигде не допустили ошибок, то после пересборки у вас должен появиться вот такой выбор в списке возможных сборок:

В принципе уже сейчас можно компилировать, жмем на молоток и видим что компиляция происходит успешно, а вот линковка нет, требуется метод __write() , который вызывается оператором вывода в main.cpp.
Все потому что мы не настроили ключи для компилятора и линковщика. Переходим к настройку 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
Переходим в настройки отладчика Run -> Edit Configurations -> Templates
И находим там Embedded GDB Server

В шаблоне нет настроек и можно для каждого проекта использовать пустой шаблон и каждый раз его настраивать, а можно сразу настроить шаблон, чтобы в следующем проекте переиспользовать настройки.
Настроим сразу шаблон:
В опции Download executable поставим галочку, на Update Only — позволит загружать в микроконтроллер образ программы только в том случае, если были были какие-то изменения, в противном случае прошивки не будет.
OpenOCD по умолчанию работает по tcp протоколу, т.е. вы можете подключаться к серверу удалённо по IP адресу и порту по умолчанию 3333 (порт можно менять, но нам это не нужно). Так как запускаться OpenOCD будет на локальном компьютере, то и в опции target remote args нужно установить в значение tcp:127.0.0.1:3333
В опции GDB Server прописываем путь к OpenOCD, туда куда вы уже его скопировали на предыдущих шагах.
В GDB Server args прописываем строку запуска OpenOCD сервера с аргументами. Так как я использую китайский клон Nucleo, который называется XNucleo, то я немного подредактировал конфигурацию st_nucelo, прописав идентификационный номер вендора китайского отладчика (hla_vid_pid — The vendor ID and product ID of the adapter) и поменял имя файла настроек. В итоге моя строка для аргументов OpenOcd выглядит следующим образом:
-f ../scripts/board/st_xnucleo_f4.cfg -c «reset_config none separate» -c «init» -c «reset halt»
Здесь ключ -f задаёт имя конфигурационного файла, вместо моего st_xnucleo_f4.cfg, поставьте вашу плату, либо если у вас нет платы, то прописать нужно конфигурацию для процессора и для отладчика в отдельном файле и уже подключить этот файл.
Ключ -с задаёт команду, которая следуют за ключем в кавычках.
-c «reset_config none separate» — означает, что сброс производится через SWD без использования отдельной ножки сброса (а у меня как раз такой китайский отладчик).
-c «init» — запускает команду «init», которая запускает загрузочные OpenOCD скрипты под ваш целевой процессор
-c «reset halt»_ — выполняет немедленный сброс микроконтроллера после инициализации
В принципе все. Больше ничего не нужно. У вас должен получиться вот такой шаблон

Осталось на основе этого шаблона создать конфигурацию:
- Снова переходим в Run -> Edit Configurations
- Жмем на «+»

и выбираем наш Template. Переименовываем как-то по человечьи

И собственно теперь можно запускать на проверку, жмем на жука и смотрим, как все работает.
В опциях Advanced GDB Server options можно дополнительно установить команды выполняющиеся после загрузки кода. Я поставил перезагрузку и перенаправление потока вывода через отладочный интерфейс — monitor arm semihosting enable . Только не забудьте поставить галочку Download executable: Always иначе загрузки не будет и команды не выполнятся.
Теперь все обращения к потоку вывода будут отражаться у вас в окне Debug: Console . Выводиться будет медленно, но для отладки пойдет.
Также вы можете просмотреть все регистры для вашего микроконтроллера но нужно будет их подключить, используя .svd файл.
Завершающий этап
Чтобы наш проект заработал вообще как надо, добавим в него файл startup.cpp , в котором будет происходить инициализация стека, инициализация статических переменных, fpu и храниться таблица векторов прерывания и собственно переход на точку входа программы main() .
Для этого нам достаточно скопировать файл startup.cpp в папку проекта и добавить его в сборку.

Теперь наш проект готов и вы можете скачать его здесь: Постой проект с настройками для IAR
Для открытия в Clion достаточно зайти в меню File->Open и выбрать папку в которую вы его разархивировали.
Да остался один момент:
Статический анализатор, проверяющий код на лету, на основе Clang пока не работает для IAR, так как не понимает ключи компилятора, поэтому его придется отключить, через меню File->Settings -> Languages&Frameworks -> C/C++ -> Clangd .
Убрать галочку Enable clangd server.

Заключение
В качестве заключения хотелось бы сказать, что работать в IAR IDE после Clion как то не очень хочется. Хотя для детальной отладки все таки придется использовать IAR, так как средства отладки там явно обширнее. С другой стороны к отладке я вообще редко обращаюсь, разве что проверить код студентов, когда он не работает.
Clion бесплатен для студентов и поэтому проблем с его установкой у них быть не должно, но и в принципе лицензия тоже не дорогая. Думаю, что студентам Clion серьезно облегчит жизнь и привнесет песчинку радости в их угрюмую жизнь, потому что сейчас больно смотреть на их муки написания кода. Да, что таить и на работе тоже.
А еще работать в Clion приятно, потому что все в одном. Например, эту статью я пишу тоже в Clion и сразу вижу её отображение.

А ведь есть еще куча всяких других плюшек, про которые я рассказывать не буду, они описаны на сайте JetBrains. Просто завершающий гифчик, показывающий скорость работы:
How do I set up CLion to compile and run?
I just downloaded CLion from https://www.jetbrains.com/ because I just love the rest of their products.
However, I’m having problems configuring it. I’m not able to compile and run my application (a simple "hello world").

When I try to run the application, it refers me to "Edit configuration", so I added a new application and now I have this problem:
- I cannot specify the "target"; the only thing I can do is set "All targets".
- I cannot specify the "configuration" (all tutorials I found have Debug or Run here).
- Executable? Hmm. Should the path to GCC be here? (C:\MinGW\bin\gcc.exe)
The rest of the configuration looks optional.
My CMakeList.txt looks like:
I tried to run this with "All targets". I also tried to set the executable. I tried everything, but I’m not able to make it work.
Can anyone advise?
![]()
3 Answers 3
I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.
The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.
SHORT ANSWER (should be similar for MinGW too but I haven’t tried it):
- Install Cygwin with GCC, G++, GDB and CMake (the required versions)
- Add full path to Cygwin ‘bin’ directory to Windows Environment variables
- Restart CLion and check ‘Settings’ -> ‘Build, Execution, Deployment’ to make sure CLion has picked up the right versions of Cygwin, make and gdb
- Check the project configuration (‘Run’ -> ‘Edit configuration’) to make sure your project name appears there and you can select options in ‘Target’, ‘Configuration’ and ‘Executable’ fields.
- Build and then Run
- Enjoy
LONG ANSWER:
Below are the detailed steps that solved this issue for me:
Uninstall/delete the previous version of Cygwin (MinGW in your case)
Make sure that CLion is up-to-date
Run Cygwin setup (x64 for my 64-bit OS)
Install at least the following packages for Cygwin: gcc g++ make Cmake gdb Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion’s Quick Start section (I cannot post more than 2 links until I have more reputation points).
Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called ‘Path’. You can Google how to find environment variables for your version of Windows
[On Win 10, right-click on ‘This PC’ and select Properties -> Advanced system settings -> Environment variables. -> under ‘System Variables’ -> find ‘Path’ -> click ‘Edit’]
Add the ‘bin’ folder to the Path variable. For Cygwin, I added: D:\cygwin64\bin
Start CLion and go to ‘Settings’ either from the ‘Welcome Screen’ or from File -> Settings
Select ‘Build, Execution, Deployment’ and then click on ‘Toolchains’
Your ‘Environment’ should show the correct path to your Cygwin installation directory (or MinGW)
For ‘CMake executable’, select ‘Use bundled CMake x.x.x’ (3.3.2 in my case at the time of writing this answer)
‘Debugger’ shown to me says ‘Cygwin GDB GNU gdb (GDB) 7.8’ [too many gdb’s in that line ;-)]
Below that it should show a checkmark for all the categories and should also show the correct path to ‘make’, ‘C compiler’ and ‘C++ compiler’
- Now go to ‘Run’ -> ‘Edit configuration’. You should see your project name in the left-side panel and the configurations on the right side
There should be no errors in the console window. You will see that the ‘Run’ -> ‘Build’ option is now active
Build your project and then run the project. You should see the output in the terminal window