Как подключить mingw к clion

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

Я только что скачал CLion с https://www.jetbrains.com/, потому что я просто обожаю остальные их продукты.

Однако у меня проблемы с его настройкой. Я не могу скомпилировать и запустить свое приложение (простой «привет мир»).

Когда я пытаюсь запустить приложение, оно ссылается на «Редактировать конфигурацию», поэтому я добавил новое приложение, и теперь у меня возникает эта проблема:

Остальная часть конфигурации выглядит необязательно.

Мой CMakeList.txt выглядит так:

Я попытался запустить это с «Все цели». Я также попытался установить исполняемый файл. Я попробовал все, но я не могу заставить его работать.

Может кто-нибудь здесь посоветовать? Благодарю.

ОТВЕТЫ

Ответ 1

Я столкнулся с той же проблемой с CLion 1.2.1 (на момент написания ответа) после обновления Windows 10. Он работал отлично, прежде чем обновил свою ОС. Моя ОС установлена ​​на диске C:\и CLion 1.2.1, а Cygwin (64-разрядная версия) установлены на диске D: \.

Проблема, похоже, связана с CMake. Я использую Cygwin. Ниже приведен короткий ответ с шагами, которые я использовал для устранения проблемы.

КРАТКОЕ ОТВЕТ (должно быть аналогично для MinGW, но я не пробовал):

ДОЛГОЙ ОТВЕТ:

Ниже приведены подробные шаги, которые решили для меня эту проблему:

Удалите/удалите предыдущую версию Cygwin (MinGW в вашем случае)

Убедитесь, что CLion обновлен

Запустите настройку Cygwin (x64 для моей 64-разрядной ОС)

Установите, по крайней мере, следующие пакеты для Cygwin: gcc g++ make Cmake gdb Убедитесь, что вы устанавливаете правильные версии вышеуказанных пакетов, которые требуется CLION. Вы можете найти требуемые номера версий в разделе быстрого цикла CLion (я не могу разместить более двух ссылок, пока у меня не будет больше точек репутации).

[В Win 10 щелкните правой кнопкой мыши на «Этот ПК» и выберите «Свойства» → «Расширенные настройки системы» → «Переменные среды». → в разделе «Системные переменные» → найдите «Путь» → нажмите «Изменить», ]

Добавьте папку «bin» в переменную Path. Для Cygwin я добавил: D:\cygwin64\bin

Запустите CLion и перейдите в «Настройки» либо с экрана приветствия, либо из файла → Настройки

В «Среда» должен отображаться правильный путь к каталогу установки Cygwin (или MinGW)

Для «исполняемого файла CMake» выберите «Использовать связанный CMake x.x.x» (3.3.2 в моем случае на момент написания ответа)

Ниже он должен показать галочку для всех категорий и должен также показать правильный путь к make, компилятору C и компилятору С++

В окне консоли не должно быть ошибок. Вы увидите, что параметр «Выполнить» → «Создать» теперь активен

Создайте проект, а затем запустите проект. Вы должны увидеть вывод в окне терминала

Надеюсь, это поможет! Удачи и наслаждайтесь CLION.

Ответ 2

Я столкнулся с некоторыми проблемами в Клионе и, наконец, решил их. Вот некоторый опыт.

Ответ 3

Вы также можете использовать компилятор Microsoft Visual Studio вместо Cygwin или MinGW в среде Windows в качестве компилятора для CLion.

Источник

Школа179

MinGW – вариант компилятора GNU C/C++ для Windows. Он используется всеми сторонними средами разработки, кроме Visual Studio, у которой собственный компилятор. Среда разработки, как правило, не связана тесно с компилятором MinGW и может использовать несколько разных версий MinGW. Компилятор MinGW может распространяться и вместе со средой разработки, как, например, Code::Blocks.

Но, в частности, среда CLion требует отдельной установки MinGW. Вы можете взять MinGW из Code::Blocks, он находится в каталоге MinGW внутри каталога, куда был установлен Code::Blocks, то есть полный путь к компилятору MinGW может быть таким: C:\Program Files (x86)\CodeBlocks\MinGW\. Или вы можете установить более новую версию компилятора отдельно – в Code::Blocks версия MinGW, как правило, довольно старая.

1. Инструкция по установке MinGW-w64

1. Скачать установщик mingw-w64-install.exe отсюда и запустить его.

Нажимаем next. Установщик скачивает информацию о доступных пакетах MinGW.

2. На следующей странице вы можете выбрать, какой вариант MinGW устанавливать: версия компилятора (последняя доступная будет 7.2.0 на начало 2018 г.), архитектуру (можно заменить 32-битную архитектуру i686 на 64-битную x86_64), другие параметры менять не следует.

3. В следующем окне задается путь для установки компилятора. Запомните этот путь или укажите другой.

4. Установщик скачивает нужные пакеты. Ждем завершения процесса.

5. Ждем появления сообщения «Click Next to continue the installation» и нажимаем Next.

6. Установка закончена.

После установки подкаталог bin каталога, куда был установлен MinGW, рекомендуется добавить в системную переменную PATH.

2. Установка и настройка Clion

Установка Clion никакой сложности не представляет. Жмём «Next» на всех экранах. Более сложна настройка CLion после запуска.

1. Здесь можно просто нажать OK. На других экранах, которые не упомянуты ниже, можно просто нажимать «Next».
file:clion1.png

2. Здесь нужно получить лицензию на использование Clion, для этого нужно ввести свой логин и пароль от кабинета на сайте jetbrains.com. Предварительно необходимо самостоятельно регистрироваться и получать лицензии на странице https://www.jetbrains.com/student/, при этом в качестве адреса электронной почты нужно указать адрес в домене @179.ru – тогда вы получите академическую лицензию на все продукты.
file:clion2.png

3. Здесь нужно добавить компилятор MinGW. Кликайте на ссылку MinGW.
file:clion2.png

Читайте также:  Модуль зажигания что это такое

4. На следующем экране нужно ввести выбрать путь к каталогу, куда установлен MinGW («Use MinGW home»). Дождитесь, пока clion определит версии компилятора и gdb.
file:clion4.png

5. На следующих экранах настраиваются дополнительные плагины, они вам не нужны, просто жмем Next.

3. Установка и настройка Code::Blocks

1. Рекомендуется скачивать Code::Blocks, содержащий компилятор MinGW, а потом исправить настройки MinGW. Ссылка для скачивания: https://sourceforge.net/projec[..]w-setup.exe/download

2. Установка Code::Blocks затруднений не представляет.

3. При первом запуске Code::Blocks обнаруживает Gnu GCC Compiler – скорее всего встроенный. Его нужно заменить на установленный MinGW. Нужно открыть меню «Settings – Compiler», На вкладке «Toolchain exacutables» Compiler’s installation directory заменить на каталог с MinGW (например, C:\soft\mingw-w64\i686-7.2.0-posix-dwarf-rt_v5-rev1\mingw32)

Источник

Как настроить Clion для компиляции и запуска

Я просто скачать Clion от https://www.jetbrains.com/ потому что я просто обожаю всю их продукцию.

однако у меня возникли проблемы с его правильной конфигурацией, отбросьте тот факт, что я пытаюсь, я не могу скомпилировать и запустить свое приложение (простой hello world one )

когда я пытаюсь запустить приложение, оно ссылается на «Редактировать конфигурацию», поэтому я добавил новое приложение и теперь проблема.

конфигурация Rest, похоже, не требуется.

Мой CMakeList.тхт выглядит так:

Я пытаюсь выполнить это с «все цели», а также попытаться setupt выполнимый. Все, но я не могу заставить его работать.

здесь кто-нибудь, у кого были эти проблемы раньше и может посоветовать? Спасибо

3 ответов

я столкнулся с такой же проблемой с CLion 1.2.1 (на момент написания этого ответа) после обновления Windows 10. Он работал нормально, прежде чем я обновил свою ОС. Моя ОС установлена на диске C:\, а CLion 1.2.1 и Cygwin (64-бит) установлены на диске D:\.

проблема, похоже, связана с CMake. Я использую Cygwin. Ниже приведен краткий ответ с шагами, которые я использовал для устранения проблемы.

КОРОТКИЙ ОТВЕТ: (должно быть похоже на MinGW тоже, но я не пробовал это):

ОТВЕТ:

Ниже приведены подробные шаги, которые решили эту проблему для меня:

удалить / удалить предыдущую версию Cygwin (MinGW в вашем дело)

убедитесь, что CLion обновлен

запустите Cygwin setup (x64 для моей 64-разрядной ОС)

установите по крайней мере следующие пакеты для Cygwin: gcc g++ make Cmake gdb Убедитесь, что вы устанавливаете правильные версии вышеуказанных пакетов, которые требуются CLion. Вы можете найти необходимые номера версий в разделе быстрого запуска CLion (я не могу опубликовать более 2 ссылок, пока у меня не будет больше репутации точки.)

затем вам нужно добавить Cygwin (или MinGW) в переменную среды Windows с именем ‘Path’. Вы можете Google, как найти переменные среды для вашей версии Windows

добавить папка » bin » для переменной Path. Для Cygwin я добавил: D:\cygwin64\bin

выберите ‘Сборка, Выполнение, Развертывание’ а затем нажмите на кнопку ‘Toolchains’

код ‘среда’ должен показывать правильный путь в каталог установки Cygwin (или MinGW)

на ‘CMake исполняемый файл’ выберите ‘используйте комплект CMake x.X. x’ (3.3.2 в моем случае на момент написания этого ответа)

‘Debugger’ показали мне говорит ‘Cygwin GDB GNU gdb (GDB) 7.8’ [слишком много gdb в этой строке ;-)]

ниже есть галочка для всех категорий и также должен отображаться правильный путь к ‘make’, ‘C compiler’ и ‘компилятор C++’

создайте свой проект, а затем запустите проект. Вы должны увидеть в окне терминала

надеюсь, что это помогает! Удачи и наслаждайтесь CLion.

Я встретил некоторые проблемы в Clion и, наконец, я решил их. Вот некоторый опыт.

вы также можете использовать компилятор Microsoft Visual Studio вместо Cygwin или MinGW в среде Windows в качестве компилятора для CLion.

просто перейдите, чтобы найти действия в справке и введите «реестр» без » и включите CLion.включить.индекса MSVC Теперь настройте toolchain с помощью компилятора Microsoft Visual Studio. (Вам нужно скачать его, если он еще не загружен)

Источник

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

Источник

Познавательно-развлекательный портал