Как добавить конфигурацию в clion
Перейти к содержимому

Как добавить конфигурацию в clion

  • автор:

Run/debug configurations

CLion uses run/debug configurations to run, debug, and test your code. Each configuration is a named set of startup properties that define what to execute and what parameters and environment should be used.

This article gives a general overview of CLion’s run/debug configuration concept. For more information, refer to CMake Application, Makefile Application, Custom Build Application, or other pages in the Run/Debug Configurations section.

To quickly access the help page describing a particular configuration, open its settings in Run | Edit Configurations and press F1 .

There are two types of run/debug configurations:

Temporary — created every time you run/debug a test, test suite, fixture, or a main() entry use the gutter icons /.

Permanent — created explicitly from a template or by saving a temporary configuration. Permanent configurations remain as part of your project until you remove them.

So whenever you run/debug or test your code, CLion either uses an existing permanent run/debug configuration or creates a new temporary one.

Permanent configurations have opaque icons while the icons of temporary configurations are semi-transparent.

The maximum number of temporary configurations is 5. The older ones are automatically deleted when new ones are added. If necessary, you can increase this limit in Settings | Advanced Settings | IDE | Temporary configurations limit .

Permanent and temporary configurations have different icons

Create permanent run/debug configurations

CLion provides the following ways to create a permanent run/debug configuration:

Create from a template or copy an existing configuration.

Save a temporary configuration as permanent

Select a temporary configuration in the run/debug configuration switcher and then click Save Configuration .

Alternatively, select a temporary configuration in the Run/debug configurations dialog and click on the toolbar.

CLion provides run/debug configuration templates for different languages, tools, and frameworks. The list of available templates varies depending on the installed and enabled plugins.

Create a run/debug configuration from a template

From the main menu, select Run | Edit Configurations . Alternatively, press Alt+Shift+F10 , then 0 .

In the Run/Debug Configuration dialog, click on the toolbar or press Alt+Insert . The list shows the run/debug configuration templates.

Specify the run/debug configuration name in the Name field. This name will be shown in the list of the available run/debug configurations.

Select Allow multiple instances if you want to allow multiple instances of the configuration to run at the same time. If this option is disabled, attempting to re-run the configuration will terminate the active session.

Depending on the chosen template, fill up the configuration settings. For example, CMake Application, Custom Build Application, Gradle / Gradle Native Application.

In the Before launch section, define whether you want to perform any specific actions before launching the application, for example, launch an external tool or another build configuration before run. To skip the build stage, remove Build from the Before launch list .

Apply the changes and close the dialog.

Share run/debug configurations

If you are working in a team, you might want to share your run/debug configurations so that your teammates could run the application using the same configuration or enable them to remotely attach to the process you are running.

For these purposes, CLion provides a mechanism to store your run/debug configurations as project files and share them through VCS. The same mechanism can also be used when you want to send your configuration as a file to someone else. This saves a lot of time as run/debug configurations sometimes get sophisticated, and keeping them in sync manually would be tedious and error-prone.

From the main menu, select Run | Edit Configurations . Alternatively, press Alt+Shift+F10 , then 0 .

Select the run/debug configuration you want to share, enable the Store as project file option, and specify the location where the configuration file will be stored.

If compatibility with CLion 2019.3 and earlier is required, store the file in the default location.

(Optional) If the .idea directory is added to VCS ignored files, the .idea/runConfigurations subfolder will be ignored, too. If you use Git for your project, you can share .idea/runConfigurations only and leave .idea ignored by modifying .gitignore as follows:

Turning on the Store as project file option does not submit anything to the VCS for you. For run/debug configurations to make their way to a shared repository, you have to check them in like other versioned files.

To learn how to import run/debug configurations from VCS, refer to the Version control section.

Run/debug configuration templates

All run/debug configurations are based on templates, which implement the startup logic, define the list of parameters and their default values. The list of available templates is predefined in the installation and can only be extended via plugins. However, you can edit default parameter values in each template to streamline the setup of new run/debug configurations.

Changing the default values of a template does not affect already existing run/debug configurations.

Configure the default values for a template

From the main menu, select Run | Edit Configurations . Alternatively, press Alt+Shift+F10 , then 0 .

In the left-hand pane of the run/debug configuration dialog, click Edit configuration templates… .

In the Run/Debug Configuration Templates dialog that opens, select a configuration type.

Specify the desired default parameters and click OK to save the template.

You can share run/debug configuration templates with your team members just like regular run/debug configurations.

Environment variables and program arguments

You can influence the runtime behavior of your app by adding program arguments and environment variables to run/debug configurations.

Add program arguments

From the main menu, select Run | Edit Configurations or choose Edit Configurations from the run/debug configurations selector on the toolbar.

In the Run/Debug Configurations dialog that opens, select a configuration where you want to pass the arguments.

Type the arguments in the Program arguments field. The arguments should be separated with spaces.

Click to expand the text field, so you can view and edit the whole list of arguments.

Add environment variables

From the main menu, select Run | Edit Configurations or choose Edit Configurations from the run/debug configurations selector on the toolbar.

In the Run/Debug Configurations dialog, select a configuration where you want to add the environment variables.

Type the variable name and value: <name>=<value> . If you add several variables, they should be separated with semicolons.

Alternatively, click and add the variable name and value to the User environment variables list.

adding environment variables

In the dialog that opens, you can also see the list of available system environment variables. Clear the System environment variables checkbox if you don’t want to use the system environment variables for the selected run/debug configuration. For CMake projects, see CMake environment.

Use the Load variables from file field to point CLion to a script that configures the environment. This option is available for CMake, Makefile, Gradle Native, Custom Build, and test configurations (Boost.Test, Catch, Google Test, Doctest, CTest).

Loading environment variables from a file

Use the following syntax for setting variables in your script:

Note that the environment created by a script is applied only to a single launch of the corresponding configuration and takes precedence over custom values.

The specified script will be run after all the Before launch steps..

Run/debug configuration folders

When there are many run/debug configurations of the same type, you can group them in folders so they become easier to distinguish visually.

Once grouped, the run/debug configurations appear in the list under the corresponding folders.

Grouped run configurations

Create a folder for run/debug configurations

From the main menu, select Run | Edit Configurations . Alternatively, press Alt+Shift+F10 , then 0 .

In the Run/Debug Configurations dialog, select a configuration type and click on the toolbar. A new empty folder for the selected type is created.

Specify the folder name in the text field to the right or accept the default name.

Select the desired run/debug configurations and move them under the target folder.

Apply the changes. If a folder is empty, it will not be saved.

When you no longer need a folder, you can delete it Delete . The run/debug configurations grouped under this folder will be moved under the root of the corresponding run/debug configuration type.

Как настроить CLion актуальной версии для запуска и компиляции

При кодировании C L ion позволяет ва м вообще забыть о рутине. Компилятор и отладка кода в C L ion просто на высоте. Вы можете четко сконцентрироваться только на важном, а все остальное этот редактор возьмет на себя. Данная IDE способна повысить в ашу производительность за счет «умного» и своевременного автозавершения кода, мгновенной навигации по документу и надежного рефакторинга.

Преимущества C L ion перед другими IDE

  1. Легкий старт. В данной IDE очень легко начать новый проект , ф айлы могут быть добавлены в проект одним щелчком мыши.
  2. Умный редактор. Благодаря своей умной среде, C L ion анализирует ваш код, понимает ваш проект и старается увеличить вашу скорость написания кода за счет интеллектуального автозавершения.
  3. Навигация и поиск. Найти необходимый «кусок» кода не составит труда — мгновенная навигация по символу, классу или файлу в этом помогает.
  4. Генерация кода и рефакторинг. C L ion экономит вам время за счет генерации кода — от геттеров/сеттеров до более сложных шаблонов.
  5. Анализ кода на лету. У вас есть возможность писать красивый и правильный код. Данная IDE «на лету» проводит статический анализ вашего кода для поддерживаемых языков , п оэтому она способна сразу показывать вам предупреждения и ошибки.
  6. Настройка редактора. Гибкая система настройки C L ion позволяет выбирать тему редактора, раскладку клавиатуры и др. В общем , позволяет вам полностью настроить C L ion под себя.
  7. Запуск и отладка C L ion. Вы можете запускать и отлаживать свою программу как локально, так и удаленно.
  8. Динамический анализ. Если использовать интеграцию с Valgrid Memcheck, Google Sanitizerz и CPU Profiler, то можно легко обнаружить ошибки в памяти, скачки данных и любую другую проблему, также можно с легкостью отслеживать производительность вашей программы.
  9. Поддержка CMake. CMake — это кроссплатформенная система сборки, которая широко используется для проектов С и С++.
  10. Модульное тестирование. CLion поддерживает платформы Google Test, Boost.Test и Catch. Также он имеет встроенный инструмент для запуска тестов.
  11. Документация по коду. В CLion легко документировать свой код. Доступен предварительный просмотр документов в стиле Doxygen во всплывающем окне.
  12. Встроенная разработка. В CLion вы легко можете разрабатывать для микроконтроллеров, используя различные возможности отладки.
  13. Интеграция VCS. Данная IDE предоставляет унифицированный интерфей с для большинства популярных VCS, таких как Git, GitHub, CVS, Perforce и другие.
  14. Удобный терминал. Вы легко можете получить доступ к командной строке через встроенный терминал, можете включить режим эмуляции Vim, можете расширить функциональность среды и другими плагинами.

Как настроить IDE CLion?

  1. Тема редактора. В настройках редактора есть возможность выбрать между светлой и темной темой оформления. Разработчикам с дальтонизмом можно попробовать параметр «Корректировать цвета красно-зеленого дефицита».
  2. Цвета и шрифты. Не стесняйтесь использовать настройки на полную. Вы свободно можете настроить макет цветов , шрифтов и синтаксиса, выделения ошибок, отладчика и т.д. Можете использовать предустановленные схемы цветов или созда ть с нуля сво и .
  3. Комбинации клавиш. IDE CLion по умолчанию предоставляет комбинации клавиш почти для каждой функции. Вы можете выбрать из списка подготовленных схем комбинаций или создать сво и .
  4. Фон редактора. Вы можете оживить редактор этой рабочей среды, установив любое фоновое изображение.
  5. Лигатуры. Если вам нравятся шрифты с лигатурами — используйте их.
  6. Семантическое выделение. Возможно , вам будет полезным способность настроить выделение каждой переменной или параметра своим цветом.

Запуск и отладка CLion

В зависимости от цели вашего проекта (CMake, Makefile, Gradle) CLion будет генерировать необходимую конфигурацию, которую можно будет запустить.

Запуск CLion

  1. Шаблоны конфигурации. Чтобы сократить время, вы можете использовать шаблоны конфигурации для модульного тестирования, удаленной отладки, запуска обычного приложения и т.д.
  2. Конфигурация запуска. Вы можете изменять исполняемый файл любой конфигурации. При желании можете сделать конфигурацию «не рабочей».
  3. Конфигурация отладки. Для старта отладки нужно нажать «Shift+F9». Чтобы проверить состояние отладки , CLion предоставляет много полезных ярлыков.

Отладка CLion

  1. Присоединение к локальному процессу. CLion позволяет отлаживать процессы на локальном компьютере, запускаемые на самом ПК, а не через IDE.
  2. Удаленная отладка GDB. Если у вас есть один запущенный исполняемый файл на локальном ПК под gdbserver, вы можете подключиться к нему с другого компьютера при помощи GDB из CLion.
  3. Контрольные точки. При старте отладки данная IDE может проверить выполнение вашего кода. Вы можете выбрать из нескольких точек останова (точки останова на стоке, символические точки останова, точки останова на исключение).
  4. Точки выполнения. С помощью действия Set Execution Point to Cursor вы можете перемещаться вперед/назад в процессе выполнения отладки, вы можете прерывать или перезапускать циклы и др.
  5. Отладка root. CLion может запускать и отлаживать вашу программу с правами root, если вы выберете эту опцию.

Мы будем очень благодарны

если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.

CLion

Крайне рекомендуется пользоваться EAP версией, ибо имеено в ней все свежие фиксы и фичи.

Установка

На официальном сайте (ссылка в header-e — кликабельна) можно найти информацию об установке через Toolbox (если вы используете другие IDE от Jetbrains) или об установке на Windows.

На Ubuntu рекомендуется следующий процесс установки (чтобы можно было обновлять среду разработки через пакетный менеджер):

clang-tidy

Clion имеет встроенный clang-tidy, но вы можете указать внешний, если он есть на вашей системе.

Нужно убедиться, что вы поставили галочку на Prefer .clang-tidy files over IDE settings чтобы использовать .clang-tidy курса.

Path: Settings / Preferences | Editor | Inspections — C/C++, General, Clang-Tidy

clang-tidy-clion

clang-format

Clion имеет встроенный (альтернативный) clang-format, но вы можете указать внешний, если он есть на вашей системе.

Нужно убедиться, что вы поставили галочку на Enable ClangFormat (only for C/C++/Objective-C чтобы использовать .clang-format курса.

Path: Settings / Preferences | Editor | Code Style — ClangFormat

clang-format-clion

Либо другой, более быстрый вариант. В нижней панели экрана, поставить соотвествующую галочку. clang-format-clion-another

Интеграция с vcpkg и CMake preets

Для начала нам нужно попасть в окно конфигурации CMake. Это происходит автоматически при первом открытии проекта или же можно найти в File -> Settings -> Build,Execution. -> CMake

cmake-configure

Для интеграции с vcpkg вне зависимости от сборки вам нужно в CMake options добавить -DCMAKE_TOOLCHAIN_FILE=<path-to-vcpkg>/vcpkg/scripts/buildsystems/vcpkg.cmake

Также, если вы пользуетесь Windows, нужно добавить -DVCPKG_TARGET_TRIPLET=x64-mingw-static для тулчейна MinGW и -DVCPKG_TARGET_TRIPLET=x64-windows-static для тулчейна MSVC/clang-cl. Дело в том, что по умолчанию vcpkg на Windows использует MS тулчейн и установленные с ним библиотеки не будут линковаться при сборке с тулчейном MinGW.

Далее добавляем три основные конфигурации, каждый раз нажимая на плюсик для создания новой конфигурации:

  • Release
    • Build type : Release
    • В CMake options добавляем —preset Release
    • Build type : Debug
    • В CMake options добавляем —preset SanitizedDebug
    • Build type : RelWithDebInfo
    • В CMake options добавляем —preset RelWithDebInfo

    Если после добавление конфигураций CMake падает с ошибкой при попытке сконфигурироваться, то нужно в каждой конфигурации указать в качестве Build directory папку вида cmake-build-<configuration-name>

    Установка и настройка компилятора и среды разработки на C++

    Студенты могут бесплатно получить лицензию на CLion и другое ПО компании JetBrains, подав заявку. Нужна почта МЭИ, фотография студенческого билета или карта ISIC.

    Установка и настройка GCC и CLion в Windows

    Инструкция по развертыванию такой же среды разработки, как в лаборатории.

    Внимание: в путях установки и в именах файлов проектов недопустимы пробелы, а в Windows — и кириллические символы.

    Требования

    • Windows 7 x64 и выше;
    • 2 ГБ оперативной памяти.

    Инструкция

    1. Скачать и установить компилятор MinGW-w64. При установке выбрать путь C:\MinGW-w64 . В случае проблем можно скопировать этот каталог из лаборатории или у коллег.
    2. Скачать и установить среду CLion.
    3. Скачать архив настроек CLion ( ) и импортировать настройки: пункт меню Configue →Import Settings стартового диалога или через пункт меню File →Import Settings. окна CLion.
    4. Установить CMake. Нужна ссылка в таблице Binary distributions!

    Наладка среды разработки для OS X (macOS)

    Студентов, которым это нужно, у нас мало, но особых проблем у них не было. Если хотите поделиться здесь своим опытом, обратитесь к Дмитрию Козлюку.

    • JetBrains AppCode — предшественница/альтернатива CLion.
    • Apple XCode — стандартная среда разработки для ОС Apple.
    • Среда разработки на основе Code::Blocks, доступна в ОС Apple, хотя преимуществ у этого решения мало.

    Наладка среды разработки в Linux

    Студентов, которым это было бы нужно, у нас еще не было. Но Вадиму Никитину и Дмитрию Козлюку — каждый день.

    • Нужен GCC и CMake, обычно это пакеты gcc и cmake .
    • CLion работает под Linux, его можно скачать там же, где и для Windows.
    • Вадим пользуется CodeLite.

    Если CLion не устраивает

    Как и всё остальное, CLion несовершенен, например, требователен к ресурсам и версии ОС. Вот несколько альтернатив.

    • Microsoft Visual Studio Community Edition очень хороша, но требовательна к ресурсам и только для Windows. Включает собственный компилятор.
    • Среда разработки на основе Code::Blocks, которая использовалась в 2013—2016 годах на Windows XP. Вместо Code::Block можно взять более продвинутую CodeLite.
    • Редактор Geany очень легковесный. Компилятор и систему сборки нужно устанавливать отдельно (можно тот же MinGW-w64).
    • Eclipse CDT: мощная, кроссплатформенная, но непростая в настройке среда. Компилятор и система сборки в комплект не входят.

    © кафедра Управления и информатики НИУ «МЭИ», 2014—2016 г. г.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *