Как выбрать компилятор в clion
Tutorial: Configure CLion on Windows
On Windows, CLion toolchains include the make utility, C and C++ compilers, debugger executables and the environment. You can select one of the pre-defined toolchain setups (MinGW, Cygwin, Microsoft Visual C++, or WSL), Remote Host, Docker) or configure a custom toolchain (System):
If you don’t need to configure custom tools or don’t want to install additional software on your system, stick to MinGW (default) as it works out-of-the-box using the MinGW toolset bundled in CLion.
For details on Remote Host toolchains, see Full Remote Mode. If you are working with a Docker container, see Docker toolchain.
MinGW
Install MinGW (optional)
Download and run the MinGW-w64 installer. It provides both 64- and 32-bit options.
In the MinGW-w64 installation wizard, make sure to select the required architecture. Note that the default suggested option is 32-bit.
Wait for installation to finish.
Although MinGW-w64 provides both 64- and 32-bit options, you can also install MinGW, the 32-bit-only version.
Wait for installation to finish.
Configure a MinGW toolchain
Wait until the tools detection finishes.
Select the Debugger : you can use either bundled GDB, your MinGW GDB, or a custom GDB binary.
The recommended option is bundled GDB, since it is guaranteed to include Python support required for CLion data renderers.
Click Apply when all the tools are set correctly.
Cygwin
Download the Cygwin installer, version 2.8 or later.
Run the installer and select the following packages:
To select a package, type its name in the Search field and set the version in the New column:
CLion will attempt to detect the Cygwin installation automatically. Check the Toolset field, and specify the path manually if required.
Windows Subsystem for Linux
You can use WSL, Windows Subsystem for Linux, as your working environment in CLion on Windows 10 (starting the Fall Creators Update version 1709, build 16299.15).
WSL toolchain enables you to build projects using CMake and compilers from Linux and run/debug on WSL without leaving CLion running on your Windows machine.
Refer to our WSL guide for details on setting up WSL on your system and configuring WSL toolchains in CLion.
Microsoft Visual C++
Install Visual Studio 2013, 2015, 2017, 2019, or 2022 on your system.
Check the Toolset field. CLion will attempt to automatically detect the installed Visual Studio distribution. If the detection fails, set the path to Visual Studio manually.
Wait until the tools detection is finished
MSVC compiler
CLion supports the Microsoft Visual C++ compiler that ships with Visual Studio 2013, 2015, 2017, and 2019.
Note that msbuild is not supported: CLion runs CMake with the NMAKE generator instead.
For the case when your code includes MSVC extensions, CLion provides the support for:
additional format specifiers, such as %I32 and %I64 ;
Clang-cl compiler
Install clang-cl from the LLVM site or along with the Visual Studio tools.
When installed from the LLVM site, the clang-cl binary can be found at the standard location C:\Program Files\LLVM\bin\clang-cl.exe for the 64-bit version or C:\Program Files (x86)\LLVM\bin\clang-cl.exe for the 32-bit version.
In CLion, go to File | Settings | Build, Execution, Deployment | Toolchains and select the Visual Studio toolchain that you want to configure, or create a new one.
MSVC debugger
The MSVC toolchain debugger is implemented on top of LLDB, and it can work with native visualizers from the Visual Studio installation or from your project.
To enable native visualizers support and set the desired diagnostics level, select the Enable NatVis renderers for LLDB checkbox in Settings | Build, Execution, Deployment | Debugger | Data Views | C/C++ :
If you have custom native visualizers in your project, CLion will use them as well.
System toolchain
Configure the tools and provide an environment script if required:
Initializing the toolchain environment via a script
Specifying an environment script is available for all toolchains. However, it is not supported for CMake presets at the moment (CPP-26576).
Environment sourcing will happen on the first actual usage of the toolchain in a CMake profile or upon loading a Makefile project.
In the Environment file field, specify the path to the script:
You will get notifications in case of script loading issues. CLion also checks the script loading time and terminates the execution if it takes too long.
Clang compiler on Windows
With CMake 3.15, it has become possible to use the Clang compiler on Windows with the MinGW-w64/MinGW toolchain.
However, the LLVM Clang for Windows is built using Microsoft Visual Studio, and all the built-in macros and include search paths are set up for use with Visual Studio. So if you take Clang from the LLVM repository, it will not work correctly when configured with the MinGW toolchain. One of the possible workarounds is described below.
Set up the Clang compiler for MinGW
This way, you will get the Clang compiler which is built with mingw-w64 and has paths and macros that correspond to this toolchain.
With this new toolchain configured, you can build the project and start using the Clang’s advances tools, such as profile-guided optimization. Take a look at our detailed blogpost for instructions.
GDB on Windows
In the case of MinGW, CLion includes the bundled GDB (version 10.2). For Cygwin, you need to install the GDB package in the Cygwin Package Manager, as described in the Cygwin section of this guide.
You can also switch to a custom GDB binary. In this case, the supported GDB versions are 7.8.x-11.1.
Настройка IDE Clion и Cmake для работы с STM32 и C++
Перед примером моей настройки немного лирики.
Давно хотел попробовать себя в микроконтроллерах, вернее были идеи с их использованием, которые очень хотелось реализовать. Сначала начал с PIC32 — огонь контроллеры. Так получалось, что поначалу и коротил их порты, и с питанием завышал — неубиваемые (не совсем конечно, порт правда однажды сгорел, но сам контроллер продолжал работу). IDE MplabX неплоха, подкупал графический блок с отображением занимаемой RAM/Flash на выбранном МК — удобно, но сам NetBeans как IDE это жесть, ну не удобно ни разу после Idea. Но проблема была не в этом — как потом оказалось, PIC’и тяжело достать, мало кто их возит, а если и возит, то по относительно высокой цене.
Дальше решил копнуть в сторону STM32 — они в больших количествах, за базовую периферию просят не много, но главное — это доставаемость. (Но кодогенератор STM’а хуже Microchip’a — весь файл загажен комментами и функциями, это конечно сильно огорчило. У Microchip’а все сгенеренные функции вынесены в отдельные файлы и main.c практически чист — прелесть).
(UPD: вот тут признаюсь ошибался, спасибо golf2109, он подсказал, что от заваливания комментами и функциями файла main.c можно избавиться, достаточно включить в настройках опцию для вынесения сгенерированного кода в отдельные файлы, но я все же в недоумении, почему это не дефолтная настройка, вроде логично было бы)
Теперь об IDE для STM32.
Попробовал хваленый Keil — конечно получше блокнота, но ужасно не удобный (ни нормальных подсказок, ни нормального форматирования, после Idea в общем не то пальто, особенно я так и не понял как создавать пакеты, почему нельзя просто в окошке ткнуть создать пакет и продолжить — матюгаться хочется).
Потом попробовал CooCox — гораздо лучше и приятнее интерфейс, хорошо настраивается форматирование (прям порадовала настройка переноса параметров в методах, да и другие настройки очень кстати), но опять же не хватало многих плюшек от Idea и опять же проблемы с организацией пакетов.
Еще из изменений — дебаггер, упомянутый в блоге, переименовали в Ozone, его еще не тестил, позже отпишусь.
И последняя проблема, сверлившая мозг. Очень хотелось ООП, но не компилился проект если я добавлял C++ файл, куча ошибок с не найденными функциями (например, _exit, _sbrk и пр.). Здесь проблем было 2:
Работать стало приятно, но пока заливаю прошивку через STM’овскую утилиту, позже попробую накрутить OZONE. На вопросы отвечу (если смогу).
Quick start guide
0. Before you start
Is CLion a cross-platform IDE?
Yes, you can install and run CLion on Windows, macOS, and Linux.
See Install CLion for OS-specific instructions.
See CLion keyboard shortcuts for instructions on how to choose the right keymap for your operating system, and learn the most useful shortcuts.
What compilers and debuggers can I work with?
In CLion, you can use GCC-based compilers, Clang, Clang-cl, Visual Studio C++ compiler, as well as IAR compiler and custom-defined compiler. See Compilers for more information.
CLion supports debugging with GDB (either bundled or custom) on all platforms and with the bundled LLDB on macOS and Linux. Also, there is an LLDB-based debugger for the MSVC toolchain on Windows. Refer to the section on debugging below and to the page on Debugger options for details.
What build systems are supported? What are the project formats?
CLion fully integrates with the CMake build system: you can create, open, build and run/debug CMake projects seamlessly. CMake itself is bundled in CLion, so you don’t need to install it separately unless you decide to use a custom version.
Apart from CMake, CLion supports Makefile, compilation database, and Gradle projects. Creating new projects of these types in CLion is not supported currently.
Refer to Project Formats for details.
Do I need to install anything in advance?
On Windows, CLion requires a working environment. CLion bundles a version of the MinGW toolset for quick setup. You can use this bundled toolchain or switch to another MinGW installation, Cygwin, or Microsoft Visual C++. If you are working with WSL or Docker, you will need to install them as well.
On macOS, the required tools might be already installed. If not, update command line developer tools as described in Configuring CLion on macOS.
On Linux, compilers and make might also be pre-installed. Otherwise, in case of Debian/Ubuntu, install the build_essentials package and, if required, the llvm package to get Clang.
Are languages other that C++ supported as well?
Yes, CLion fully supports Python, Objective-C/C++, HTML (including HTML5), CSS, JavaScript, and XML. Support for these languages is implemented via the bundled plugins, which are enabled by default. See CLion features in different languages for more details.
You can install other plugins to get more languages supported in CLion (such as Rust, Swift, or Markdown). See Valuable language plugins.
1. Open/create a project
Open a local project
For CMake projects, use one of the following options:
Select File | Open and locate the project directory. This directory should contain a CMakeLists.txt file.
Checkout from a repository
Click Checkout from Version Control on the Welcome screen or select VCS | Checkout from Version Control from the main menu and choose your version control system.
Enter the credentials to access the storage and provide the path to the sources. CLion will clone the repository to a new CMake project.
Create a new CMake project
Select File | New Project from the main menu or click New Project on the Welcome screen.
Set the type of your project: C or C++, an executable or a library.
Note that STM32CubeMX and CUDA are also CMake-based project types.
Provide the root folder location and select the language standard.
CLion creates a new CMake project and fills in the top-level CMakeLists.txt :
The initial CMakeLists.txt file already contains several commands. Find their description and more information on working with CMake in our tutorial.
2. Take a look around
Project view shows your project files and directories. From here, you can manage project folders (mark them as sources, libraries, or excluded items), add new files, reload the project, and call for other actions such as Recompile.
Navigation bar helps you switch between the files’ tabs, and the Toolbar provides quick access to run/debug and VSC-related actions.
Right gutter shows the code analysis results with the overall file status indicator at the top.
Tool windows represent specific tools or tasks such as TODOs, CMake, terminal, or file structure.
Status bar shows various indicators for your project and the entire IDE: file encoding, line separator, memory usage, and others. Also, here you can find the resolve context switcher.
Any time you need to find an IDE action, press Ctrl+Shift+A or go to Help | Find Action and start typing the name of a command, setting, or even a UI element that you are looking for:
3. Customize your environment
Change the IDE appearance
The quickest way to switch between the IDE’s color schemes, code styles, keymaps, viewing modes, and look-and-feels (UI themes) is the Switch. pop-up. To invoke it, click View | Quick Switch Scheme or press Ctrl+` :
Tune the editor
Pages under the Editor node of the Settings / Preferences dialog help you adjust the editor’s behavior, from the most general settings (like Drag’n’Drop enabling and scroll configuration) to highlighting colors and code style options.
Adjust the keymap
There are also plugins that extend the list of available keymaps. For example, VS Code Keymap or Vim emulation (which includes the Vim keymap). Find more useful plugins for the CLion editor in Valuable non-bundled plugins.
4. Code with assistance
Auto-completion
Basic completion Ctrl+Space in CLion works as you type and gives a list of all available completions. To filter this list and see only the suggestions that match the expected type, use Smart completion Ctrl+Shift+Space :
Code generation
Even an empty class or a new C/C++ file contains boilerplate code, which CLion generates automatically. For example, when you add a new class, CLion creates a header with stub code and header guard already placed inside, and the corresponding source file that includes it.
To get the list of code generation options at any place in your code, press Alt+Insert to invoke the Generate menu:
These options can help you skip a lot of code writing. In addition to generating constructors/destructors, getters/setters, and various operators, you can quickly override and implement functions:
Intentions and quick-fixes
When you see a light bulb next to a symbol in your code, it means that CLion’s code analysis has found a potential problem or a possible change to be made:
Click the light bulb icon (or press Alt+Enter ) and choose the most suitable action or quick-fix:
Inspections
During on-the-fly code analysis, CLion highlights suspicious code and shows colored stripes in the right-hand gutter. You can hover the mouse over a stripe to view the problem description and click it to jump to the corresponding issue. The sign at the top of the gutter indicates the overall file status:
CLion detects not only compilation errors but also code inefficiencies like unused variables or dead code. Also, it integrates a customizable set of Clang-tidy checks.
You can also run inspections on demand for the whole project or a custom scope, and view the results in a separate window. For this, call Code | Inspect Code or use Code | Analyze Code | Run Inspection by Name Ctrl+Alt+Shift+I for a particular inspection.
From the results tool window, you can batch-apply quick fixes for several issues at a time. Click Fix partially in the description tab:
Refactorings
Refactorings help improve your code without adding new functionality, making it cleaner and easier to read and maintain. Use the Refactor section of the main menu or call Refactor This. Ctrl+Alt+Shift+T to get the list of refactorings available at the current location:
Rename Shift+F6 renames a symbol in all references;
Change Signature Ctrl+F6 adds, removes, or reorders function parameters, changes the return type, or updates the function name (affecting all usages);
Inline Ctrl+Alt+N /Extract inlines or extracts a function, typedef, variable, parameter, define, or constant;
Pull Members Up/Down ( Refactor | Pull Members Up / Push Members Down ) safely moves class members to the base or subclass.
5. Explore your code
Search everywhere
Find usages
To locate the usage of any code symbol, call Find Usages ( Alt+F7 or Edit | Find | Find Usages ). You can filter the results and jump back to the source code:
Navigate in the code structure
Switch between header and source file Ctrl+Alt+Home
Go to declaration/definition Ctrl+B Ctrl+Alt+B
Show file structure Alt+7
View type hierarchy Ctrl+H
View call hierarchy Ctrl+Alt+H
View import hierarchy Alt+Shift+H
For your code, CLion builds the hierarchies of types, call, imports, and functions. To view them, use the shortcuts given above or the commands in the Navigate menu. For example, type hierarchy helps you not only to navigate the code but also to discover what type relationships exist in the your codebase:
To explore the structure of the currently opened file, call View | Tool windows | Structure or press Alt+7 :
View pop-up documentation
Quick Documentation popup (available on mousehover or via the Ctrl+Q shortcut) helps you get more information on a symbol at caret without leaving the current context. Depending on the element you invoke it for, the popup shows:
function signature details,
code documentation (either regular or Doxygen comments),
inferred types for variables declared as auto :
formatted macro expansions :
Besides, you can instantly view the definition of a symbol at caret. Press Ctrl+Shift+I to invoke the Quick Definition popup:
6. Build and run
Run/Debug configurations
For each target in your project, CLion creates a run/debug configuration. It is a named setup which includes target, executable, arguments to pass to the program, and other options.
Edit Configurations dialog is accessible from the Run menu or the configuration switcher. Here you can manage the templates and add, delete, or edit your configurations.
For example, you can customize the steps to be taken Before launch : call external tools (including the remote ones), use CMake install, or even run another configuration.
Build actions
Build is included in many Run/Debug configuration templates as a default pre-launch step. However, you can also perform it separately by calling the desired action from the Build menu:
Notice the Recompile option that compiles a selected file without building the whole project.
Remote and embedded development
With CLion, you can also build and run/debug on remote machines including embedded targets. See the sections on Remote development and Embedded development.
7. Debug
CLion integrates with the GDB backend on all platforms (on Windows, the bundled GDB is available only for MinGW) and LLDB on macOS/Linux. You can switch to a custom version of GDB on all platforms. Also, CLion provides an LLDB-based debugger for MSVC on Windows.
Currently, the versions of the bundled debuggers are the following:
LLDB v 13.0.0 for macOS/Linux and 9.0.0 for Windows (MSVC)
GDB v 10.2 for macOS
GDB v 10.2 for Windows
GDB v 10.2 for Linux
Custom GDB v 7.8.x-11.1
Compilers
Toolchain compilers (IDE-wide)
The compilers you configure in the currently selected toolchain are used for all the projects you work with in CLion.
By default, CLion detects the compilers from the provided environment (for example, MinGW, Cygwin, or Microsoft Visual C++ on Windows) along with other tools.
Change toolchain compilers
Go to Settings / Preferences | Build, Execution, Deployment | Toolchains and select the toolchain you want to edit.
In the C++ Compiler or C Compiler fields specify the path to the desired installation, for example:
Project compilers
If you need to use non-default compilers, you can change the paths in toolchain settings (IDE-wide) or set the compilers manually, affecting the current project only.
In case your project specifies the compilers that differ from those set in the toolchain, CLion will use the project ones.
Compilers for Cmake projects
For CMake projects, you can change the compilers in the CMake profile settings defined per project.
Change CMake profile compilers
In the CMake options field, specify the compiler by setting the CMAKE_LANG_COMPILER variable:
The LANG part specifies the language ( C for C and CXX for C++), and you need to provide the full path to the compiler, for example:
After you apply the settings, CLion will reset the CMake cache and reload your project.