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

Как запустить программу в clion

  • автор:

Run/debug single file

In CLion, you can compile and run/debug a single file without creating, loading, and building a whole project. This is especially useful if you are getting started with the C or C++ language, and have only one or two files that you want to compile and run. In this case, the concept of a project model might seem too complex and redundant for you.

Follow the steps below to open, compile and run or debug a file in CLion without attaching it to any project model.

1. Open a file/folder and set initial configuration

Click Open on the Welcome screen or select File | Open from the main menu:

You can either open a file or a folder containing one or several files:

Select the file:

Opening a single file

Opening a file as project

Click Open as project :

Initial configuration dialog

You will see a configuration dialog. Here you can set additional run/debug parameters.

Opening a containing folder to run single file

Select the folder where your C/C++ file or files are located:

The folder/file will be opened without a project model.

On top of the source file containing main , you will see a yellow pane. You can safely ignore it and proceed with running the file from the gutter menu (see below). Optionally, you can click Configure for the current file , and CLion will open the configuration dialog.

File or folder opened without a project model

2. Run/debug a file using the gutter menu

In the editor, click the left gutter icon next to your program’s entry point:

If you select Run , the file will be compiled and run, and you will see the results in the Run tool window:

Running a single file from gutter

Similarly, you can select Debug (make sure to place breakpoints in your code beforehand), and CLion will compile the file and launch a debug session.

For debug, CLion automatically adds the compiler flags required for generating debug information (such as -g for GCC and Clang, or similar options for MSVC).

3. Adjust the automatically created configuration

When you use the gutter menu to run/debug a file, CLion automatically creates a run/debug configuration of the type C/C++ File . This configuration allows you to quickly configure the toolchain, manage source files, and add compilation options.

To access the configuration settings, do one of the following:

Click Edit Configurations in the configuration switcher:

From the gutter menu, select Modify Run Configuration :

Go to Run | Edit Configurations. on the main menu, then select the configuration in the list (its name will be similar to the name of the file).

In the Edit Configuration dialog, you can adjust the settings of compilation and run. For example, add the required compiler options:

Adding compiler options to C/C++ File configuration

By default, CLion uses cc and c++ compilers on macOS and Linux and cl.exe on Windows. If you need to change that, use Additional options | Compiler path field. Note that Docker and remote toolchains are not supported.

When you run a file or create a C/C++ File configuration, the information is stored in the .idea directory inside your folder. This allows you to re-open your folder later and not lose your configurations.

4. (Optional) Save the automatically created configuration

The configuration that CLion creates automatically is a temporary one and will be removed after the maximum number of temporary configurations is reached. To save it for further use, do one of the following:

Saving a configuration from the switcher

In the configuration switcher, select Save ‘configuration_name’ Configuration :

Select the configuration in the Edit Configurations dialog and click on the toolbar:

5. (Optional) Add C/C++ File configurations manually

You can create more configurations of the C/C++ File type.

To access the configuration wizard, go to Run | Edit Configurations or click Configure for the current file on top of your source file.

In the Run/Debug Configuration dialog, click on the toolbar or press Alt+Insert . Select C/C++ File from the list of templates:

Provide the name for your configuration, select the source file, and set additional options if required.

Hello! Let’s start with CLion

Hello! My name is Vladyslav Batyrenko, I’m a student living in Kyiv, Ukraine. This is my first GSoC blog post about my participating in Ark project. In this post I would like to tell you how I managed to set up my environment for coding with CLion, utilizing it not only as an editor but also as a debugging tool. You may think that’s a trivial task almost every IDE can handle — and this is true, but until your project requires a non-trivial deployment process before it is able to start. So if you want to know how to build, deploy and run/debug your executable with pressing only (SHIFT+F10) buttons, you may find this post useful.

This was a thorny way with doing a lot of workarounds…

Getting started

CLion is an IDE from JetBrains, it has a very rich set of features. You can easily get it from its official site. Here I’ll use Ark project I’ll be working on as an example for setting up CLion.

git clone git://anongit.kde.org/ark

Ark uses CMake for building and it’s a fortune because so does CLion. After opening the project in the IDE and trying to run it (Run -> Run) or (SHIFT+F10) you must get “Unable to find Ark’s KPart component, please check your installation.” error. That’s it. We’ll want to run make install for built project and to run installed executable. For accomplishing this task CLion provides us with External tool functionality.

After spending much time on researching, how exactly I can make CLion run installed executable I came up with the following solution… If someone has another ideas please feel free to share them, that’s only how I myself managed to workaround the situation.

Setting up the project in CLion

External tool allows us to run a custom bash script before/after build step.

Firstly, I though, I needed to somehow make CMake communicate with my bash script in order to get my script to know where the build directory is. CLion generates random path (for our perception) for its CMake binary dir… I had, for instance, /home/mvlabat/.CLion2016.1/system/cmake/generated/ark-e86190eb/e86190eb/Debug .

So I’ve ended up with adding to Ark target’s CMakeList.txt file the following lines:

After each build command this will create the file called “cmake_binary_dir” with a path to CMAKE_BINARY_DIR.

Secondly, I had to set the environmental variables for building and running processes. On Ark page in KDE Community Wiki it is stated that we have to set these variables:

Alright, said — done. We have to go to both CLion CMake options
(File -> Settings (CTRL+ALT+S) -> Build, Execution, Deployment -> CMake)
and target’s build options
(Run -> Edit Configurations. ) (ALT+SHIFT+F10 and then press 0) ,
where we’ll set them.

Environment Variables

Be aware! CLion, unfortunately, doesn’t allow to use bash variables here, so you won’t be able to write something like “/custom/folder/bin:$PATH”. So check you variables from terminal with echo $VARIABLE and paste needed values manually.
Correct me if it is/will be wrong, I’ll become happy.

Finally, we can add our bash script. Don’t leave target’s build options. At the bottom you’ll see the pane, which contains “Build” command running before launch. Here we can add our external tool, which will be a bash script.

After Install script

(On the screenshot you may see a little difference, I just pressed edit buttons in order to show you my existing External Tool, while you’ll have to add your own.)

And there are the contents of the script:

P.S. Remember to replace the according strings with your install path.

Running

Now we can start our happy debuggin! 🙂

Set your break points, then just press ALT+SHIFT+F9 , select Ark target (later you can just use SHIFT+F9 ) and enjoy! I hope everything will work on your local machines.

If you have any problems, questions, marks, feel free to comment this post.

Getting started with CLion

Analysis Situs

Once you eventually get tired with Windows (in my situation, the performance of OS somehow degraded after a couple of years working), you might find yourself in a dilemma. Either you simply trash your existing system to reinstall it from scratch, or probably it’s the right time to pick up an alternative system to the rescue. The recent release of Ubuntu Linux seems just fine for starters: you will not have any trouble browsing the internet, watching videos, listening to music, etc. The only puzzle piece that I missed a lot was a decent IDE for C++ programming. Some years ago, I used Eclipse, then tried to start with the Qt Creator and had eventually fallen to the simplistic Visual Studio Code editor, which is not that bad by the way. I also remember the feeling when getting back from Eclipse to Visual Studio 2005. That time I got to know what catharsis is: you get a light and fast IDE (yeah, MS Visual Studio was like that) instead of an always-busy though open-source (does that excuse?) IDE.

So here is the question: which IDE is good on Linux? Without an aim to get into a holy war, I just want to share some thoughts on using the CLion IDE, which a commercial product (so, yeah, you have to pay for it). Take what’s written below with a grain a salt, because:

  1. I am a beginner with CLion. This blog post is written right after I managed to burn down the first bug in one of my projects, so the IDE was in productive use. At the same time, to fully appreciate an IDE, you have to use it for months.
  2. I did use some other IDEs like Eclipse (10 years ago or so). I’m not a fan of Eclipse and based on my old experience, I try to avoid this IDE as much as possible. Probably this IDE is much better now compared to what it was when I did some Java programming. But the memories are full of pain.

Getting started on Windows

CLion can easily be downloaded from the website of JetBrains. I started to test it on Windows, which is still my central working system for all the projects I’m doing (primarily because of Visual Studio). I was not aware of JetBrains and their products before. That’s likely because I’m not on the cutting edge of technology. In fact, you do not need that much to feel comfortable with geometric modeling which is my domain. Surrounding your favorite set of proven libs (like Qt, OpenCascade, VTK, etc.) with a good enough IDE, you will not feel like the rest of the world is moving somewhere ahead while you’re stuck with your grandfather’s tools. Either it is our field that is so conservative or it’s rather me who is too lazy to keep up with all sorts of exciting technologies and languages emerging every year or so.

After several hours of googling, I started to appreciate the message of JetBrains to the market. They make tools for the software developers, and, since they are the developers by themselves, they “eat their own dog food” (JetBrains seem to like that saying) to feel their products better and improve them based on their own experience. This is a brilliant practice, indeed. We follow the same style of work in our CAD Processor product. Even the superb QA team will not give the level of confidence and satisfaction that you gain from your own experience of using your tool for solving your own problems. JetBrains is also known for its Kotlin programming language. A company ambitious enough to start inventing a new programming language deserves some attention for sure.

CLion is the IDE. It is by no means a compiler or a configuration system. The toolchain for building your projects can be configured right after you launch the IDE first time. I picked up the existing MSVC toolset (Visual Studio 2017 Professional in my case) as the “Environment” to let the IDE find all other things by itself. Besides automatic lookup for the C/C++ compiler and debugger, CLion also detects the CMake binaries (it has a CMake bundle inside). As I’m using CMake whenever I can, that was another pleasant surprise: so far, the configuration process had been pretty straightforward. I don’t know, though, how easy it would be in the case when you do not migrate from an already deployed development environment (with all these Visual Studios and CMakes over there), but start from a blank sheet.

The GUI of CLion looks pretty attractive. It natively supports a dark and a white theme, where my favorite dark one looks polished enough (this theme is named “Darcula” in CLion). Although I would prefer a bit more contrast in the dark theme, it is still much better than something I was manually configuring in Visual Studio 2010 a long time ago. Not bad. The documentation available on the website is looking good as well.

The configuration process in CLion is tightly coupled with CMake. To switch between the build types (i.e., Release vs Debug), one has to go to the CMake props in the corresponding GUI panel of CLion. On CMake reconfiguration, the IDE will create a build directory (by default, this is a directory right within the source folder) named to reflect the build type (with “-debug” and “-release” suffix).

Do not forget to select the target architecture (x86 or x64) properly. The default value is x86 and this was an improper setting in my environment. Such a misconfiguration will remain unnoticed until the build is finished (unsuccessfully).

Instead of opening CMake GUI which was quite a familiar utility for me, in CLion I used to adjust all the CMake variables right in the CMakeCache.txt file. Not sure if that’s the as-designed way of configuration, but given that the CMake output is always at hand, such a new technique does not seem impractical. Am I missing some more elaborated way of configuration though?

Running from IDE

In Visual Studio, we used to set the Environment property for debugging right away from the IDE.

Visual Studio allows specifying the environment PATH variable to assure that all the runtime libraries are picked up when the executable runs. The missing environment was the first painful thing I faced in CLion. Even though your project builds successfully, it would not launch unless you have all the dependency libs (“so” for Linux and “dll” for Windows) in the runtime path. After spending a couple of hours on the internet, I discovered a lack of best practices to grab along the migration journey. There is plenty of youtube videos speaking about refactoring tools and smooth CMake integration where CLion seems to excel. But there are too few (if any) tutorials on how to set up the things for an existing (you can put “legacy” here) industrial project. Such projects are so different from the “Hello World” apps, so I wonder how scalable CLion is. Will it work well for a project with millions of lines of code? Will these refactoring tools be that efficient for such a vast code base? After all, does that matter in terms of efficiency that CLion is a Java-based app? One link to check out is the CLion performance tuning tips.

After a few hours of debugging, I discovered that CLion (in fact, JVM) does not release memory even after the app is stopped. To free the allocated RAM it seems necessary to kill the “java” process, though such killing will certainly shut down the IDE. Does anybody have a clue on that? Or am I doing something stupid on my side?

Returning to the environment issue, one can fix that by going into “Edit Configurations…” panel and adding the variables manually there. Not so different from the familiar Visual Studio’s way of doing that.

Two questions remain with such an approach:

  1. How to set up different runtime variables for debug and release? You should never mix both.
  2. How to avoid manual configuration of the environment? I.e., when a project is cloned from a repo first time, you’ll unlikely want to spend a couple of unforgettable hours figuring out how to run it from within IDE.

The IDE settings for a project are available in .idea/workspace.xml file. It includes the environment variables that you set for your runtime. According to how JetBrains recommends to configure your .gitignore, the workspace.xml file is machine-dependent, so it should not be shared with a team. On the other hand, it is probably possible to generalize these XML files to avoid full paths. Like this, we should be able to share the runtime environment, thus preventing the need for local configuration.

Post-build testing?

In Analysis Situs we use a post-build event to run unit testing right after the build process is done. In CLion, such a technique does not work anymore. The logic of running unit tests was configured in the following way in CMake:

It appears that such a trick is not only OS-specific (it was excluded from the Linux configuration), but also IDE-specific. There are integrations of CLion with some decent unit testing frameworks like Google Test, but I would not really want to refactor the unit testing system because of IDE. The easiest way to get unblocked is to temporarily disable unit tests. For that, in CMake, one can check if the CLION_IDE variable is defined, and, if so, do not include the corresponding targets into the project.

Getting started on Linux

The installation on Linux is as simple as on Windows. After downloading the CLion tarball from the JetBrains’ website, simply unpack it to the system directory:

The process of importing the existing CMake project and compiling it was quite straightforward. As in the case of Windows, I had to manually change the CMakeCache.txt file to set up all configuration variables. After spending like ten minutes on that, I strengthened in the opinion that it would be much better to have a simplistic UI for CMake. Is there one? If yes, then how to enable it? But, Ok, even modifying the cache this way, you don’t face any blocking issues.

Once the project is compiled, it’s time to run and debug it. As personally, I have difficulties with debugging on Linux (yes, I hate debugging in the console), a simple ability of visual inspection at runtime, going into and over, setting breakpoints, etc. is a huge deal by itself for me. It does not really matter which IDE uncovers that creepy GDB into something eatable. What matters is how simple the configuration process is. So that was the moment of truth. As expected, I could not simply run the compiled application as the dependency libraries were neither in the working directory nor in the system path (there should have been Qt, VTK, OpenCascade, and many more). So I had to set the LD_LIBRARY_PATH variable in a custom way. Here is when I made the first mistake: you have to set your environment for executable, and not in the global settings. Before discovering that (I have to admit, that’s quite logical, so it was entirely my fault), I tried to verify things by setting and printing the LD_LIBRARY_PATH in the terminal. Although the documentation says that there is a Terminal window, I could not enable it for a while. Accidentally, I found that you have to turn on a hardly perceptible checkbox for the corresponding (and pre-installed) plugin in the settings panel. This is how it looks like (notice a small checkbox on the right):

The terminal was enabled. It was of little help, though, as the environment variables I set there did not have any effect on running. Again, be careful to specify your custom environment: do this in the settings of your executable.

Conclusion

To fairly assess one or another IDE, you need to have been working with it for a while. Ideally, the projects you’re doing should not be like self-contained student’s exercises. Otherwise, you’ll get no idea how good the IDE is when applied to real industrial programming. Some of the things I liked about CLion product are listed below:

  1. It is easy to install and configure. Probably, that’s because I had almost all my projects in CMake already. That was a perfect fit for me, but I’m not sure if my experience scales.
  2. The GUI is friendly. Some little settings which I could not find out reading the online documentation or watching the overview videos, I had eventually sorted out by myself intuitively.
  3. The IDE looks powerful. It provides a lot of tools for working with the semantics of your code, including all sorts of finders, macro expansion utilities, refactoring recipes, and many more. Do not forget about static code analyzers and integrations with such popular tools as Valgrind. I have not evaluated all the options currently as such experimenting takes a lot of time.
  4. The guys who develop CLion have published many introductory videos, including insightful conference talks. Watch them out to learn the IDE better: it worth the time you spend on it.

Some questions remain, though. As anyone who has been caught by the first-class Visual Studio workbench, I’ve got difficulties trying to establish the familiar way of working in the new IDE. Many questions like the one with unit tests remain unresolved for me. Also, although looking nice in general, the UI of IDE is subjectively worse than in Microsoft products. I did not like the very contrasting Project tree in the Darcula scheme: it distracts a lot from the editor because of the too-bright font color. The layout of GUI controls also looks a bit messy to me (probably because of fonts again). Some panels (like the Terminal one) are hard to activate. The hotkeys are different from the familiar Visual Studio combinations, and I still have a hard time switching between both.

I also failed to find a CMake configuration panel to avoid editing CMakeCache.txt file manually (that could be Ok for open-source tools, but not for a commercial-grade IDE). I asked the question about CMake configuration in the recent webinar by JetBrains devoted to CLion. Here is my question:

“When configuring my project, I use to edit CMakeCache.txt file manually to set CMake variables. I have a feeling that it’s not the as-designed way of CMake configuration in CLion. Am I missing some easier way of doing this, e.g., a dedicated GUI for typing CMake variables? I would expect something like good old familiar cmake-gui.”

And the answer was:

“You still can do manually in CMakeCache. But there are also these settings: follow the link.”

So we can define some variables, but it’s not like using cmake-gui anyway.

No doubts, after spending several months in the IDE, one gets used to all sorts of inconsistencies and finds some tricks to stay productive. Despite the fact the CLion is based on the good old IntelliJ IDEA, there’s hope that the development team of CLion is not too restricted within the cage of the base framework. However, they are probably limited by Java more than by their in-house codes. I was really disappointed to see how much memory does JVM consume after several trial and error debugging attempts. You should keep an eye on your RAM resources and kill Java from time to time. That’s too bad. If that goes like this, the next IDE I’ll choose for C++ (in case CLion won’t take off) will not be based on Java. Does anybody know some good cross-platform IDEs with CMake support and without any Java inside?

I asked the question of unreleased memory in the recent webinar by JetBrains devoted to CLion. Here is my question:

“Sometimes after debugging I see that RAM is not released even if the program being debugged is closed. I use to kill the CLion process and restart it to overcome that problem. Does anybody face similar issues on debugging? CLion 2020.1.1, Linux Ubuntu 18_04.”

And the answer was:

“Maybe you can report, with some additional logs (as described here).”

So it’s apparently not something everybody faces every single day. It is considered a bug and that sounds promising.

Well, the IDE is not expensive after all. For a small amount of money (that should not be a problem for any working programmer) you rent a tool of good quality, and the tool pays for itself.

Как настроить 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, если вы выберете эту опцию.

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

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

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

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