Clion Multiple Main In One Project


I have made it work in both Windows 10 and Linux (Ubuntu 16.04) after a lot of searching on Google. Apparently it's not so easy to find after all. So, I am gonna put an end to this problem now and here. Open CLion, if you end up in the Welcome Window then click on Open and select the root of LAMMPS directory. If you end up in the main window with an already opened project, you can go to Open ➡️ File ➡️ Open. And select the root of LAMMPS directory. To enable CMake project, open cmake/CMakeLists.txt. You can have more than one main in the same project, if to each main will correspond a different executable in the build directory tree. The following example is using CMake, I don't know if it can be done with other build-process manager software.


The Bazel plugin for CLion does not support macOS, per

This guide describes how to set up Drake in the JetBrains CLion IDE on Ubuntu.

First, you must install Bazel and build Drake with Bazel, followingthe Drake Bazel instructions.

To use Drake with CLion, your Drake checkout must be named drake.

Installing CLion

  1. Go to Look for “Other versions”and download the appropriate version of CLion (see below).
  2. Install CLion. Exact steps depend on your platform, but it’sstraightforward. Just using defaults for everything is fine. You now have a30-day trial version of CLion. Either try it out as is, or get a freeacademic license here.

The most recent versions that we have tested for compatibility are:

Clion Multiple Main In One Projector

  • Ubuntu 18.04
  • Bazel 3.0.0 (6 April 2020)
  • CLion 2019.3.6 (5 May 2020) with:
    • Bazel plugin 2020. (15 June 2020).

Many versions of the above (Bazel / CLion / Bazel plugin) are not compatiblewith each other. We strongly suggest using only the versions shown above, whenworking with Drake.

Upgrading CLion

Users upgrading from a previous version of CLion should do the following:

  1. To have your Unity launcher CLion icon point to the correct version,run locate jetbrains-clion.desktop and edit the located file. If morethan one file is located, you may want to consolidate to a single launch filein your user directory, typically ~/.local/share/applications.
  2. Uninstall the previous version of the Bazel plugin and update to the latestversion. See Installing the Bazel Plugin.

Note: It is not necessary to import your project into a new CLion project.Overwriting the old project is appropriate.

Installing the Bazel Plugin

To use Bazel in CLion, you must install a plugin supplied by Google. Toinstall the plugin, open Settings (either Welcome > Configure >Settings or File > Settings), select Plugins, and press the Browserepositories button. Locate and install the Bazel plugin. You will beprompted to restart CLion.

To use Drake in CLion you must use Drake’s bazel wrapper.Open Settings > Bazel Settings. For Bazel binary location select thepath to drake/tools/clion/bazel_wrapper from any recent Drake source tree(it doesn’t have to match the current project open in CLion).

Setting up Drake in CLion

CLion will invoke Bazel to build Drake, including the external dependenciesspecified in the WORKSPACE file.

  1. File > Import Bazel Project
  2. Select Workspace: Use an existing Bazel workspace, and provide the path toyour drake directory.
  3. Select Project View: choose “Import project view file”, andselect the file drake/.bazelproject
  4. Project View: Pick a project data directory of your choice for theCLion project files. It must not be a subdirectory of drake.
  5. (Advanced) Project View: If you only wish to develop a subset of Drake,you can specify only those files and targets in the project view file.Most users should leave it as-is.
  6. Click “Finish”. CLion will begin ingesting the Drake source, buildingsymbols, and compiling Drake. This will take several minutes.

Building and Running Targets

To build all of Drake with default Bazel options, selectBazel > Build > Compile Project.

To build or run a specific target go to Run > Edit Configurations. Click+ to create a new Bazel command. Specify the configuration name and Bazeloptions. The Target expression specifies the actual code (library, binary,and/or test) that you want to run. To learn more about target expressions, seethe Bazel manual.Once you’ve created a configuration, you can launch it from the Run menu.

To run a specific target in the debugger, create a configuration as above,using the bazel run command. Then launch it from Run > Debug.

Keeping CLion Up-to-Date with the Bazel Build

Changes to BUILD files can add or remove source files from the Bazel build.To propagate those changes into the CLion project structure, selectBazel > Sync Project With BUILD Files.

Git Integration

CLion provides a user interface for Git, which you can enable in the VCSmenu. It automatically detects all Git roots within the workspace. This willinclude bazel-drake, which is a Bazel-internal detail. Bazel editsthe contents of that directory for its own purposes, and those changes willspuriously appear in the CLion UI as changes that need to be committed. To makeCLion ignore bazel-drake, enable Git integration under the VCStab, then go to File > Settings. Select the Version Control menu itemdirectly (not one of the subtopics displayed when that item is expanded). Youwill see a list of all the Git root directories. Look for bazel-drakeon that list and select it. On the right hand side are + and - buttons;click - to remove the spurious root directory. After that you should beable to go to VCS > Commit Changes and there should be no changes seen.

CLion provides a mechanism for invoking external binaries/scripts/etc. withparameters derived from the CLion GUI. Below, we outline a number of commontools to aid with compliance with the Drake style guide. The work to createa new external tool is the same in all cases; only the specific tool settingsdiffer from tool to tool. We’ll outline the general work here and provideper-tool details below. The GUI description applies to version 2018.1.6 andmay be slightly different in previous versions.

  1. Open the Settings dialog (File > Settings) or Alt+Ctrl+S.
  2. Navigate to Tools > External Tools.
  3. Click the + sign to add a newtool.
  4. Set the appropriate fields in the Edit Tool. See the following tools fordetails.
  5. Click Ok.

There are several ways to use an External Tool. One is to right-click on afile and select External Tools > Tool Name. Another is to selectTools > External Tools > Tool Name. For tools that operate on aselected file, make sure that file is “active” by clicking on it. TheTool Name will be the value set in the Name field outlined below.

Formatting files

You can use clang format to modify the formatting of your file in the GUI. We’llintroduce three variants:

  • Apply clang-format to a whole file.
  • Apply clang-format to selected lines.
  • Apply clang-format to correct #include ordering.

These tools modify the selected file. There is a synchronization issue withCLion such that the modification may not be immediately apparent. When in doubt,select away from the target file and back; this will cause the file to refreshand you can confirm that the file has been modified as expected.

First, make sure you have installed clang-format-9(see Tools for Code Style Compliance).

Clang format selected file

Open the Edit Tool for external tools as outlined above and enter thefollowing values for the fields:

  • Name:Clang Format Full File
  • Description:Apply clang-format to the active file
  • Program:clang-format-9
  • Arguments:-i $FileName$
  • Working directory:$FileDir$
  • Advanced Options: Uncheck Open console for tool output

Leave the checkbox options in their default state.

Clang format selected lines

Open the Edit Tool for external tools as outlined above and enter thefollowing values for the fields:

Clion Multiple Main In One Project
  • Name:Clang Format Selected Lines
  • Description:Apply clang-format to the selected lines
  • Program:clang-format-9
  • Arguments:-lines $SelectionStartLine$:$SelectionEndLine$ -i $FileName$
  • Working directory:$FileDir$
  • Advanced Options: Uncheck Open console for tool output

Leave the checkbox options in their default state.

Correct #include ordering

Open the Edit Tool for external tools as outlined above and enter thefollowing values for the fields:

  • Name:Clang Format Include Ordering
  • Description:Runs the clang format for correcting includes on the current file
  • Program:bazel
  • Arguments:run //tools/lint:clang-format-includes -- $FilePath$
  • Working directory:$Projectpath$
  • Advanced Options: Uncheck Open console for tool output

Leave the checkbox options in their default state.

“Linting” files

“Linting” refers to using tools to find aspects of code which don’t conformto specified coding practices. You can apply Drake’s linting tools in CLion tofind such issues. We’ll define two tools:

  • General linting (via cpplint) which captures most of the Drake style guide.
  • Drake extended linting which captures aspects of the Drake style guide notcaptured by the general linting tool. This includes detecting out-of-order#include directives.

These tools produce reports. In some cases, the reports can be automaticallyconverted into clickable links so that you can click on a message and be takento the file and line indicated in the message. The configuration instructionsinclude the details of how to configure these clickable links.

You can also set the general coding style for CLion through the following steps

  1. Go to File > Settings > Editor > Code Style
  2. On the right panel, Go to Default Options > Right margin (columns):Set it to 80
  3. Go to File > Settings > Editor > Code Style > C/C++
  4. On the right panel, choose Set from > Predefined Style > Google

Lint selected file for google style guide

Open the Edit Tool for external tools as outlined above and enter thefollowing values for the fields:

  • Name:Cpplint File
  • Description:Apply cpplint to the current file
  • Program:bazel
  • Arguments:run @styleguide//:cpplint -- --output=eclipse $FilePath$
  • Working directory:$Projectpath$
  • Advanced Options: Confirm Open console for tool output is checked

To configure the clickable links, enter the following string in the AdvancedOptions > Output filters window:


Lint selected file for Drake style addenda

This tool is a supplement to the google style cpplint. It tests for additionalstyle requirements which are otherwise missed by the general tool. The primaryreason to run this is to confirm that the order of the #include statementsis correct.

Open the Edit Tool for external tools as outlined above and enter thefollowing values for the fields:

  • Name:Drake Lint File
  • Description:Apply drake lint to the current file
  • Program:bazel
  • Arguments:run //tools/lint:drakelint -- $FilePath$
  • Working directory:$Projectpath$
  • Advanced Options: Confirm Open console for tool output is checked

In the event of finding a lint problem (e.g., out-of-order include files), theCLion output will contain a single clickable link. This link is only thefirst error encountered in the include section; there may be more. The linkmerely provides a hint to the developer to see the problem area. Rather thanfixing by hand, we strongly recommend executing the Clang Format IncludeOrdering external tool on the file.

Alternative linting configuration

The linting tools have been configured to use the bazel system. The advantage indoing so is that it guarantees that the tools are built prior to being used.However, bazel only allows one instance of bazel to run at a time. For example,if building Drake in a command-line window, it would be impossible to lint filesat the same time.

The work around is to change the configurations to execute the binariesdirectly. This approach generally works but will fail if the corresponding bazeltargets have not been built. The tools would need to be built prior toexecution.

With this warning in place, you can make the following modifications to thelinting tools to be able to lint and compile simultaneously.

Google style guide linting

Change the following fields in the instructions given above:

  • Program:bazel-bin/external/styleguide/cpplint_binary
  • Arguments:--output=eclipse $FilePath$

Building the google styleguide lint tool:

bazel build @styleguide//:cpplint

Drake style addenda

Change the following fields in the instructions given above:

  • Program:bazel-bin/tools/lint/drakelint
  • Arguments:$FilePath$

Building the drake addenda lint tool:

bazel build //tools/lint:drakelint

Apparently CLion (or perhaps the Bazel plugin) has a certain amount ofauto-configuration of run/debug targets. It appears to hinge on the presence ofthe gtest.h header in source files. This is convenient, but only furthermystifies the process of debugging a non-gtest program. This section explainshow to configure debugging support for arbitrary programs in a Drake/CLionproject.

This section assumes all of the Drake-recommended installation andconfiguration is done.

Get the bazel target string

Find the source file of the program in the file tree view. Right-click on thefile, and select “Copy BUILD Target String”. This will put the Bazel targetname into the clipboard.

Start a run configuration

From the top menu, select “Run/Edit Configurations…”. Select the “+” at theupper left of the dialog to add a new configuration. From the list, select“Bazel Command”.

Fill in the configuration

Now it’s time to fill in the new blank configuration. Give it a name, thenselect the “+” at the right side to add the target expression. Once the editbox appears, paste the contents of the clipboard there. Hit “Enter” or “Tab” toconfirm the setting; a port number value should appear in the “Port number”field below. In “Bazel command”, select either “run” (for an arbitraryprogram), or “test” (for a Bazel test target). Everything else can be left atdefault values. Click OK to finish.

Launch the debugger

At this point, the top menu “Run” should have entries to run or debug the newconfiguration. Select the debug entry there, or use the controls at the upperright to launch the debugger.

Clion multiple main in one project managementTips & Tricks

Many developers are playing with Arduino-based projects these days. Arduino is easy to get started with, and the experience of seeing the outcome of your coding efforts in a light blinking or robot moving is delightful. But most of these Arduino developers don’t move forward. They keep working on their projects as weekend warriors, treating them simply as small hobbies and side projects. In this series of blog posts we’d like to explore how you can bring your pet projects to a more professional level and how IDEs like CLion can help you do that.

What we’re going to build

We’ve set ourselves an ambitious goal for the project. We’re going to build an electronic barograph, which is a device that measures atmospheric pressure and plots it on a chart to predict weather conditions for the next several hours. This is more useful than a classic barometer, as pressure changes are more important to track than the absolute value. The device should be battery-operated, and it should be able to work for several weeks on one charge.

We’ll start by building classic project – a DIY barometer – and we’ll use:

  • Bosch BMP085 air pressure sensor. We’ll use a GY-65 module, though it may be replaced with a BMP180 (GY-68).
  • Arduino Uno Board. We’re using a DFRduino UNO R3 because of its colorful connectors 🙂
  • Waveshare 4.2inch e-Paper screen.
  • Wires, a USB cable, several plastic PCB standoffs, M3 bolts, and nuts.
  • IKEA plastic tablet stand, for fastening all the prototype parts together.

Sounding fun yet? Let’s get started!

Starting with a prototype

Electronics setup

We’ve started by drilling several holes in the tablet stand, and we then mounted all the parts on it. One of the bolts holding the Arduino board holds the sensor module, as well.

The e-Paper screen module utilises a uni-directional SPI interface (CS, MOSI,SCK), two input control signals (RESET, DC), and a BUSY output signal. The module is shipped together with an 8-wire cable, which I connected to Arduino with the help of the 2.54mm edge pin headers. To minimize the number of headers we need to use, we connect the display power lines to the power pins of the Atmega8 in-circuit serial programming (ICSP) header. The pressure sensor uses an I2C interface (SCA, SCL) and is connected with standard F-M jumper wires.

All the connections are described in the table below:

Now it’s time to code some of our Arduino prototype.

Bring the pressure sensor online

The official Arduino guide explains Arduino sketch development in detail. So we’ll just briefly go through the setup:

  1. Create a new project and give it a name.
  2. Then add the Adafruit_BMP085 library with the Sketch -> Include Library… -> Manage Libraries… menu item.
  3. Now it’s time to add some actual code, like this.
  4. After that, you can connect your Arduino, upload the sketch, and verify that it works using the Arduino Serial monitor.

Bring the screen online

For this project, I used the code shared by the WaveShare, the screen vendor, on GitHub, and I added some more code to get our screen up and running. You can check out the final project code here. And now let’s run it!

Arduino sketches

“Sketch” is the name that Arduino uses for a program. It’s the unit of code that is uploaded to and run on an Arduino board. The languages used by Arduino sketches are C and C++. More precisely, a set of C/C++ functions can be written, and then it undergoes some preprocessing, as when one or more Arduino-specific #include clauses are added for example. The result is finally passed directly to a C/C++ compiler (avr-g++). You can read about the Arduino build process in the official documentation.

Since ultimately only C++ is being used, any general-purpose C++ IDE can be used to write the code. Using an IDE other than the Arduino one does require some manual steps, which you can extract from the official build process description. But let’s see whether you can get any benefit in return!

How CLion can help

If you are interested in embedded development and you’re looking for a project to try it out, Arduino is a good place to start. It has a huge and welcoming community, a rich infrastructure, and dozens of various code samples and libraries. It’s a perfect fit for someone looking to take their first steps in the embedded world or someone who wants to realize some simple idea. As the project grows, it starts to require more effort, more complicated code, higher embedded processor performance, more MCU memory, and more peripherals. At this point, development tools, such as IDEs, become useful for maintaining the quality of our code and helping us develop more productively. Let’s take a look at how CLion can help.

A smarter code editor with a wide reach

In case you aren’t familiar with it, CLion is a general-purpose cross-platform IDE for C and C++. It understands code in C and C++ and uses this knowledge to provide in-editor actions. Navigation actions, which can search for context usages or jump to a class, file, or symbol in one keystroke, a smart quick documentation popup, and parameter names hints help developers read and understand the code better. Autocompletion, live templates, refactorings (like extract function, parameter or variable, inline, and of course rename and change signature) all help you write your code faster. And when it comes to a code quality, the built-in static analysis tools and dynamic analysis are essential helpers. The cost of a mistake in the embedded development world can be much higher than elsewhere, as mistakes often show up at runtime when the software is running on hardware. Catching bugs right as you’re typing the code, then, obviously reduces the hassle you could face down the line.

Another great opportunity that CLion provides is the ability to debug your code. It lets you follow code execution line-by-line, check the values of variables, watch the content of peripheral registers, and more. This can all be done either in an emulator or right on a real MCU, depending on whether the right emulator exists and what the debugging capabilities of the MCU are.

You can download CLion from our site and follow this Quick Start Guide to easily get started with it. There are also two videos we recommend beginning with – CLion Quick Tour and this more detailed (and thus longer) productivity demo.

You can also learn how to configure CLion on Windows, including the necessary toolchains for compiling and debugging, from this dedicated tutorial. In our Arduino case, you will need to have MinGW installed.

Share your projects with the world

As a hobby project evolves, it usually ends up being shared on GitHub, GitLab, Bitbucket, or somewhere else, which allows more contributors to join in. Publishing on VCS, dealing with pull requests, spreading the work among several branches – all these essential tasks can be done right in CLion. As for editing the code, uncommitted changes are highlighted in the editor, and authors’ annotations are available. All of these features reduce the need to switch contexts, saving you time for working out your new ideas.

There is a nice overview video about VCS support in all IntelliJ-based IDEs, such as CLion.

By the way, when publishing to VCS, don’t forget to add a file that lets others know what the project is about and that provides details about how to work with it (what setup is required, which toolchain to use, etc.). CLion comes with Markdown support out of the box, so you’ll easily get a preview of your file:

Migrate to PlatformIO is a rich ecosystem for embedded development that supports a variety of target hardware types, compilers, and frameworks, including Arduino projects.

Let’s see how you can get started with PlatformIO in CLion:

  1. First of all, you need to install PlatformIO Core.
  2. And the PlatformIO plugin for CLion (Settings/Preferences Plugins).

Now we are ready to create a new PlatformIO project, and in our case we’ll choose Arduino Uno. Click File->New Project and select Arduino Uno as a target along with a project location. Since there are a lot of boards on the list, you can start just typing “Uno” and then use the arrow keys to navigate the list of boards. To avoid glitches later, we do not recommend using international characters, special symbols, or spaces in the location.

The next step is to enable our sensor library. Open platformio.ini in the CLion editor and add the line “lib_deps = Adafruit BMP085 Library” to the [env:uno] section, then call Tools PlatformIO Re-Init.

Now it’s time to add some code to our project. Copy all the header files from the Arduino sketch folder into the project’s include folder, and copy all source files and .ino files from the Arduino sketch folder into the project’s src folder. You can delete the empty main.c file – we don’t need that.

As we are not relying on the Arduino IDE for Arduino related preprocessor transformations, we need to perform some additional steps manually:

  1. Convert the sketch into C++. To do this, you can simply Rename (Shift+F6) the main .ino file to .cpp. In this case, CMake files will automatically be updated accordingly by CLion. And afterward you only need to reload the CMake project: Tools CMake Reload CMake project.
  2. Open arduino-barograph.cpp and add #include <Arduino.h> to the very beginning of the file.

You can now build the project! Let’s start it.


Connect your electronic device to the computer, then start the Platformio Upload run configuration. The firmware is now flashed to MCU, and our device works again. That was easy!

Let’s take a step back and look at what we’ve managed to achieve so far:

  1. We started using some additional software (PlatformIO, CLion) to get a more powerful embedded environment and to benefit from the productivity features of the C++ IDE.
  2. Thanks to the PlatformIO approach, the application can be easily migrated to many other hardware platforms with limited effort.
  3. We’ve made maintenance of the project lifecycle more convenient by using the VCS integration and Markdown support in CLion.

Taking control of the project

PlatformIO was really helpful, but what if you want to take full control of the project and customize the build steps? We’ll now convert our project into a pure CMake project. This will involve using the CLion IDE, the CMake build system, the GCC for AVR toolchain, and the avrdude flashing utility.

We’ll continue to use the Arduino libraries. The AVR toolchain can be downloaded from the Microchip site, and avrdude utility from Savannah.

In CLion, the toolchain and CMake profile are configured in the following way:

The code of the project itself can be found on GitHub. It’s the same PlatformIO code with the Arduino libraries manually-copied to the project sources. Feel free to clone and use it. However you should be careful when it comes to these user-dependant parameters in the CMakeLists.txt file:

  • avrdude location
  • Arduino COM port name
  • Special build target FLASH.

When everything is set up correctly, you can trigger the Build action in CLion (not Run!), and it will try to flash your Arduino:

Let’s see how this compares to our previous setup with PlatformIO:

  1. We need to take care of more settings, like COM port names, avrdude location, etc.
  2. We are now in full control of the build process and can tune it to our needs.
  3. The application can be migrated to other hardware platforms (even those that are not supported by PlatformIO).

Clion Multiple Main In One Project Management

What’s next

We now have an early prototype up and running that uses the bare minimum number of components and has limited functionally. How can we improve it?

  1. Better representation
    With this big screen, current weather and time data can be shown using much bigger digits. This requires more ROM memory for fonts. Arduino still has quite a lot of free flash memory, and we can probably implement the larger font with the current hardware setup.
  2. Pressure chart
    Atmospheric pressure is important for predicting the weather, but tracking its change over time is actually even more helpful. We have quite a big screen, and a pressure chart definitely fits onto it. To draw such a chart, we need a real time clock circuit (RTC) because the on-board oscillator is not precise enough to measure time.
    Arduino has only 2KB of memory, but a 400*300 black-white screen requires 15KB of memory (400*300/8 = 15KB) for off-screen graphics manipulations. This gives us the idea to replace the MCU. Note that some modern MCUs are really inexpensive and contain both enough RAM and the RTC on-chip.
  3. Battery power
    This kind of device can be optimized for power consumption, and if it’s done well, a very small battery can allow it to work for several months at a time. Unfortunately, Arduino has a USB-UART adapter and a power LED that is always on. So, to decrease consumption, we need either make our own board or do some hardware modding to the board we have already. If we change the electronics, we could switch to another MCU or board that is more power-efficient. AVR MCUs were developed a while ago, and modern electronics technology is much better in terms of power consumption.
  4. Development process
    To support all the enhancements mentioned above, we need to write some additional code. And we definitely need to test it! Arduino and AVR MCUs in general only give us the option to send diagnostics via UART. However, many other MCUs nowadays can suggest more options here. For example, on-chip debugging features allow the developer to follow code execution and variable values while the code is run on the actual MCU.

To be continued…

Clion Project Structure

This series will be continued. Soon we’ll discuss advancing this project further by using another development board and trying to utilize the best of it’s features. So stay tuned! And let us know in comments which aspects embedded development in general and Arduino in particular you’d like us to highlight.

Your CLion team
The Drive to Develop