Установка mingw для windows

Last Updated :
06 Feb, 2023

MinGW is a native C/C++ compiler(GCC) which have free distributable import libraries and header files for building native Windows applications. In this tutorial, we are going to install MinGW for C/C++. These are a few steps that we have to perform to successfully install MinGW on our device. 

How to Install the MinGW Tools for C/C++?

Step 1: Go to the MinGW website and click on Download. It will start downloading in 5 seconds.

Step 2: Double click and open the exe MinGW file and click install. It will automatically start downloading all the setups for the MinGW. 
Step 3: After all of the setup click Continue. Now the MinGW installation manager will pop up.

Step 4: In the installation manager right click on every option and then click Mark for Installation

Step 5: In the Installation, option-click Apply changes. And then select Apply. It will start downloading all the files. It will take 5-6 minutes. After finishing click on Close. 

How to Change Environment Variables for MinGW

After successful installation of MinGW, next step is to change the environment location for MinGW.

Step 1:  Go to the C drive on your device and search for the MinGW folder. And in the MinGW folder go to the bin folder and copy its path.

Step 2: Go to the control panel then go to System then Advanced system settings and then Environment variables. 

Step 3: In the system variables search for path and then select Edit. Now add a new path to it by clicking New. Now paste the path and click ok. 

This marks the complete installation of MinGW in the system.

Another method to change Environment Variable for MinGw.

Step 1:  Go to the C drive on your device and search for the MinGW folder. And in the MinGW folder go to the bin folder and copy its path.

Step 2: Now go to this pc and right click there and click on show more properties and click on properties pointed by the arrow.

Step 3: Now click on Advanced system setting.

Step 4: Now click on environmental variables.

Step 5: Now in system variables click on path and click on edit button.

Step 6: Now click on new button and paste the copied path there as shown in photo.

Now click on “ok” button of step 6, 5 and 4. and then close all the windows and restart your pc.

This marks the complete installation of MinGW in the system.

MinGW also called as Minimalistic GNU for Windows is a popular compiler for C and C++ and used for the development of native MS-Windows applications. It does not depend on any 3rd party tools or libraries but relies on the several DLLs provided by Microsoft as components of the operating system. Out of these DLLs, MSVCRT.DLL i.e. Microsoft C runtime library is the primary one. Apart from the system components, the threaded applications must use freely distributable thread support DLL, provided as part of MinGW itself. You may consider using Cygwin for POSIX application deployment.

Below listed are the features and components provided by MinGW. You may also refer MinGW for more details.

  • A port of the GNU Compiler Collection (GCC), including C, C++, ADA and Fortran compilers;
  • GNU Binutils for Windows (assembler, linker, archive manager)
  • A command-line installer, with optional GUI front-end, (mingw-get) for MinGW and MSYS deployment on MS-Windows
  • A GUI first-time setup tool (mingw-get-setup), to get you up and running with mingw-get.
     

In this tutorial, we will install MinGW on windows and write, compile, and execute our Hello World program in C++.

Step 1: Download MinGW

Go to the Download Page to start downloading mingw-w64. It will show various download options as shown in Fig 1.

MinGW Download

Fig 1

Download MinGW-W64-builds as highlighted in Fig 1.

You may also download and install MinGW Installation Manager in case you are planning only for the 32-bit compiler. The MinGW-W64 provides both 32-bit and 64-bit compilers.

MinGW Download

Fig 2

Download MinGW Installation Manager as highlighted in Fig 2.

Step 2: Install MinGW-W64

Now execute the MinGW-W64-builds executable downloaded by us in the previous step. It will show the welcome screen as shown in Fig 3.

MinGW-W64 Welcome

Fig 3

Click on the Next Button to continue with the installation. It will show the settings screen as shown in Fig 4.

MinGW-W64 Settings

Fig 4

Note that I have selected x86_64 architecture in order to support 64-bit instructions. You may continue with i686 for 32-bit instructions. Also, I have selected the posix option of Threads settings for programs involving multithreading. You may select the win32 option based on your needs. Now click on the Next Button to continue with the installation. The next screen asks for the installation path as shown in Fig 5.

MinGW-W64 Installation Path

Fig 5

Make sure that you provide an installation path without any spaces. Now click on the Next Button to finish the installation.

It might show you error specific to fail to download. I tried a few times and got success in 3rd attempt. You may also continue with manual installation in case it failed multiple times. You can simply download the archive of MinGW-W64 and extract it to the desired location.

It will show the download progress and status as shown in Fig 6, Fig 7, and Fig 8.

MinGW-W64 Downloading

Fig 6

MinGW-W64 Download Progress

Fig 7

MinGW-W64 Downloaded

Fig 8

Now click on the Next Button after download completes. It will show the success message as shown in Fig 9.

MinGW-W64 Installed

Fig 9

Click on the Finish Button to close the installer. Now add the bind directory of MinGW-W64 to the system path as shown in Fig 10.

MinGW-W64 System Path

Fig 10

Step 3: Install MinGW

In this step, we will install the MinGW distributed by the official website as shown in Fig 2. Execute the installer downloaded in previous steps. It will show the welcome screen as shown in Fig 11.

MinGW Welcome

Fig 11

Click on the Install Button to start the installation. It will ask for the installation directory as shown in Fig 12.

MinGW Installation Path

Fig 12

Click on the Continue Button to start the installation. It will show the progress as shown in Fig 13 and Fig 14.

MinGW Installation

Fig 13

MinGW Downloaded

Fig 14

Click on the Continue Button to launch the installation manger as shown in Fig 15.

MinGW Installation Manager

Fig 15

Choose the package GCC as shown in Fig 16.

MinGW Installation Manager GCC

Fig 16

Click on the Apply Button to apply the changes as shown in Fig 17.

MinGW Installation Manager Apply

Fig 17

Click on the Apply Changes Button. It will show the confirmation message as shown in Fig 18.

MinGW Installation Manager Package

Fig 18

Click on the Apply Button to install GCC. It will show the Package progress as shown in Fig 19 and Fig 20.

MinGW Installation Manager Progress

Fig 19

MinGW Installation Manager Finish

Fig 20

Click on the Close Icon and also close the installation manager to complete the installation of the compiler required to compile the programs.

You may add the MinGW path to bin directory which is C:\cpp\mingw\bin in my case to system path as we did for MinGW-W64. Make sure that you keep only one compiler path at a time among MinGW and MinGW-W64.

Step 4: Getting started with C — Hello World

Write your first C program as shown below and save in a file hello.c.

#include<stdio.h>

int main() {
	printf( "Hello World" );
}

Compile and execute the program using the command as shown below.

# Compile and make executable
gcc hello.c -o hello.exe

It will compile the program and generate the executable i.e. hello.exe. We can simply type hello to execute the program. It will print Hello World on the console as shown in Fig 21.

MinGW C Output

Fig 21

Step 5: Getting started with C++ — Hello World

We can repeat the previous step to write the Hello World program in C++. Write your first C++ program as shown below and save it to hello.cpp.

#include<iostream>  
using namespace std; 
int main() { cout << "Hello World"; return 0; }

Compile and execute the program using the command as shown below.

# Compile and make executable
g++ hello.cpp -o hello.exe

It will compile the program and generate the executable i.e. hello.exe. We can simply type hello to execute the program. It will print Hello World on the console as shown in Fig 22.

MinGW C++ Output

Fig 22

This is how we can install MinGW and MinGW-W64 and configure the system path to access the executables from the command line. We also wrote our first C and CPP programs, compiled and executed them to print Hello World on the console.

Цель статьи

Быстро, кратко, понятно описать свой личный опыт, что к чему (не супер программист, так что ввязывать в споры по типу, что один компилятор собирает программу на целых 20 килобайт меньше, итоговая программа быстрее на 200 миллисекунд или алгоритмы оптимизации лучше в Clang нежели в gcc, я не буду).

Просто кратко как, что сделать с чего начать и чем закончить.

Начало

Для начала стоит понимать, что gcc компилятор по сути сборник компиляторов для C/C++/D/Ada и др. (весь список или для любителей прямых источников) и в будущем, возможно других языков программирования. Хотя изначально разрабатывался только для C (первоначально аббревиатура расшифровывалась как GCC — GNU C Compiler (GNU компилятор для языки Си), а ныне GCC — GNU Compilers Collection (коллекция компиляторов) ).

Сама же приставка GNU отсылает нас к лицензии, используемой в данном проекте и к операционной системе GNU. Хотя скорее в целом к проекту GNU. Т.к. GNU является организацией по распространению и развитию open source решений.

Версии GCC

Так получилось, что изначально gcc идет исключительно под Linux/Unix подобные операционные системы, со всеми вытекающими несовместимостями с Windows окружением. Поэтому энтузиастами были собраны 2 различные версии GCC — Cygwin и MinGW.

Разница в том, что Cygwin эмулирует окружение Unix — подобных операционных систем прямо внутри Windows.

MinGW — по сути прямой (насколько возможно) порт GCC на Windows.

Я лично буду использовать MinGW т.к. привык к Windows, а на мой взгляд он чуть проще да и размеры бинарных файлов (исполняемых файлов) у него куда меньше т.к. отпадает нужна в эмуляции Unix-окружения.

Так что по сути и Cygwin и MinGW являются GCC компиляторами, но только это разные сборки сделанные по разным идеологиям и причинам.

Установка MinGW

Есть много вариантов (как и всегда для открытого ПО), но главных по сути 2:

  • Использовать MSYS пакетный менеджер (доступен для Windows)

  • Напрямую загрузить только MinGW.

Я буду действовать по наиболее простому и прямому пути без лишних «зависимостей» потому напрямую скачаю MinGW.

Страница для MinGW и репозиторий с готовыми билдами MinGW (ссылка взята со страницы для MinGW). Перейдя по ним, сразу видим много билдов, и с ходу не понятно какой выбрать. Но все просто. То что начинается с i686 (сильно упрощая — есть 32 bit версия компилятора), а то что начинается с x86_64 64 bit версия компилятора, действительная разница в том, что сборке в 32 bit версии не сможет генерировать 64 bit программы т.е. для ваших программ будет доступно максимум 4 Гб оперативной памяти (что для абсолютного большинства программ более чем достаточно).

Далее mcf/posix/win32. MCF — модель потоков GCC, Posix — порт предназначенный для опять же эмуляции Unix/Linux путей (но тут могу ошибаться т.к. сам не тестировал и не пробовал, что к чему). Win32 — название от winapi32, родной порт для Windows.

SEH/Dwarf — модель обработки исключений, но этот пункт имеет значение для более продвинутых останавливать не вижу смысла, проще — можно выбрать любой, когда поймете зачем он вам и в чем разница сами выберите нужный.

UCRT/MSVCRT — стандартная библиотека для языков и ее реализация. Для более менее правильно работы рекомендую MSVCRT т.к. используется стандартная библиотека времени выполнения от Windows. UCRT стандартная библиотека больше ориентированная для Linux/Unix систем т.к. для них изначально и разрабатывалась, хотя вполне работает и на Windows. Но со сборкой некоторых библиотек на C/C++ могут возникнуть проблемы.

Промежуточный итог

Это был крайне короткий и простой для понимания новичков, обзор, что к чему. Много мест где мог допустить неточность или ошибиться, но опять же вся информация из моего опыта работы с GCC.

Установка

Как такового процесса установки нет, т.к. это не в полном смысле программа или приложения, а просто собранные в архив бинарные файлы.

Но «установка» не сложна. Требуется лишь выбрать нужный каталог на вашем ПК, туда распаковать ранее скаченный архив и ВАЖНО! прописать к нему путь в системной переменной Path. Для чего это нужно, чтобы при вызове из командой строки фразы «gcc» операционная система понимала к какому именно файлу из тысяч других нужно обратиться.

Проще всего будет сделать через графический интерфейс самой Windows хотя можно и через командную строку.

  1. Открыть мой компьютер (проводник) — корневой каталог где находятся диски или диск (Локальный диск (C:), Локальный диск (D:) — (если имеется) и др.).

  2. Кликнуть ПКМ на любое свободное место и в выпадающем меню перейти в свойства.

  3. Далее в перейти в дополнительные параметры.

  4. Далее в переменные среды.

  5. В разделе системные переменные найти в колонке «переменная» название Path, нажать на нее и далее нажать изменить.

  6. И можете в начало а можете и в конец вставить полный путь к тому месту где у вас находится компилятор MinGW, например у меня это D:\mingw64. Главное вы НЕ ДОЛЖНЫ удалять или изменять содержимое данной переменной, а просто дополнить ее новым путем отделенным от других точкой с запятой (;), например D:\mingw64;C:\Program Files\Python312\Scripts. Но и в интернете есть куча более подробных статей на эту тему том числе со скриншотами и посвященными именно MinGW.

Итог

Установленный и настроенный MinGW. Чтобы убедиться, что вы все сделали правильно откройте командную строку и введите gcc —version если windows пишет что такой команды не существует значит, вы что-то сделали неправильно пересмотрите шаги. Если выведет информацию о текущей версии gcc компилятора и некоторые другие данные, значит gcc в вашей системе успешно установлен и готов к работе.

Introduction

In this blog post, I’m excited to introduce a recent project of mine aimed at simplifying the often intricate process of setting up and configuring the MinGW environment. It’s no secret that navigating the complexities of MinGW installation can be daunting, especially for newcomers. Many budding developers find themselves overwhelmed and discouraged at this initial stage. With this project, my goal is to eliminate these barriers by providing a user-friendly MinGW installer. This installer is designed to streamline the process, equipping users with a fully functional environment that includes the latest GCC version and other essential production packages.

Packages

This installer is bundled with essential and commonly used packages which includes:

  • GCC
  • GDB
  • MinGW-w64 (linked with ucrt)
  • GNU Binutils
  • GNU Make
  • PExports
  • dos2unix
  • Yasm
  • NASM
  • JWasm
  • ccache
  • CMake
  • ninja
  • Doxygen
  • Universal Ctags
  • Cppcheck

Thread model: posix

Runtime library: UCRT (Windows 10 or higher, or when Update for Universal C Runtime is installed on older Windows versions, not supported on systems older than Windows 7 SP1 and Windows Server 2008 R2 SP1)

Installation Guide

  • Download the exe file from github release or webpage
  • Run the downloaded exe file.
  • Read Package Info (Optional)
  • Click Install.

By following these simple steps, you’ll complete the setup process, and your MinGW environment will be ready to use.

Thats it. You’ve successfully completed the setup.

Video Tutorial

Easy.MinGW.Installer.Tutorial.Project.mp4

Verification and Testing

To ensure your newly set up MinGW environment is functioning seamlessly, follow these quick verification steps:

  • Open terminal/cmd
  • Type gcc -v and hit Enter
  • You will see some texts and versions like below
    Using built-in specs.
    COLLECT_GCC=C:\MinGW64\bin\gcc.exe
    COLLECT_LTO_WRAPPER=C:/MinGW64/bin/../libexec/gcc/x86_64-w64-mingw32/13.2.0/lto-wrapper.exe
    OFFLOAD_TARGET_NAMES=nvptx-none
    Target: x86_64-w64-mingw32
    Configured with: ../configure --prefix=/R/winlibs64ucrt_stage/inst_gcc-13.2.0/share/gcc --build=x86_64-w64-mingw32 --host=x86_64-w64-mingw32 --enable-offload-targets=nvptx-none --with-pkgversion='MinGW-W64 x86_64-ucrt-posix-seh, built by Brecht Sanders' --with-tune=generic --enable-checking=release --enable-threads=posix --disable-sjlj-exceptions --disable-libunwind-exceptions --disable-serial-configure --disable-bootstrap --enable-host-shared --enable-plugin --disable-default-ssp --disable-rpath --disable-libstdcxx-debug --disable-version-specific-runtime-libs --with-stabs --disable-symvers --enable-languages=c,c++,fortran,lto,objc,obj-c++ --disable-gold --disable-nls --disable-stage1-checking --disable-win32-registry --disable-multilib --enable-ld --enable-libquadmath --enable-libada --enable-libssp --enable-libstdcxx --enable-lto --enable-fully-dynamic-string --enable-libgomp --enable-graphite --enable-mingw-wildcard --enable-libstdcxx-time --enable-libstdcxx-pch --with-mpc=/d/Prog/winlibs64ucrt_stage/custombuilt --with-mpfr=/d/Prog/winlibs64ucrt_stage/custombuilt --with-gmp=/d/Prog/winlibs64ucrt_stage/custombuilt --with-isl=/d/Prog/winlibs64ucrt_stage/custombuilt --disable-libstdcxx-backtrace --enable-install-libiberty --enable-__cxa_atexit --without-included-gettext --with-diagnostics-color=auto --enable-clocale=generic --with-libiconv --with-system-zlib --with-build-sysroot=/R/winlibs64ucrt_stage/gcc-13.2.0/build_mingw/mingw-w64 CFLAGS='-I/d/Prog/winlibs64ucrt_stage/custombuilt/include/libdl-win32 -Wno-int-conversion  -march=nocona -msahf -mtune=generic -O2' CXXFLAGS='-Wno-int-conversion  -march=nocona -msahf -mtune=generic -O2' LDFLAGS='-pthread -Wl,--no-insert-timestamp -Wl,--dynamicbase -Wl,--high-entropy-va -Wl,--nxcompat -Wl,--tsaware'
    Thread model: posix
    Supported LTO compression algorithms: zlib zstd
    gcc version 13.2.0 (MinGW-W64 x86_64-ucrt-posix-seh, built by Brecht Sanders)
    

Remember the versions you see might be different from these depending on when you follow this post.

If the output matches above, congratulations! Your MinGW installation/setup is successfully done.

How to Install GCC/G++ MinGW on Windows


The default compiler for Microsoft Windows is MSVC and it is installed when we install Visual Studio. Despite being a very powerful IDE, I recommend it for almost all situations, some libraries are more practical to work with in a more minimalist environment and this can be achieved using GCC/G++ on Windows.

The package developed by GNU to get you to use gcc/g++ on Windows is MinGW .

In this article we will see how to install on Windows 10 in the most basic and minimalist way possible!

Let’s go step by step!


1. Downloading MinGW

Access the address: https://sourceforge.net/projects/mingw-w64/ in the tab: Files and in MinGW-W64 GCC-8.1.0 (if you have a later version, choose her) and download the file:
x86_64-posix-seh and after downloaded: unzip the file:

gcc/g++ MinGW Windows 1

2. Installation

Move the unzipped folder to the C:\ drive and copy the address of the bin subfolder the full path is: C:\mingw64\bin

3. Create Environment Variables

Search the Startbar for the word Environment Variables , click on the first option and then on the button: Environment Variables, a new window will open:

In the bottom box (System Variables), select Path and click on the Edit button, in the window that opened click on the New button and paste the path address: C:\mingw64\bin:

gcc/g++ MinGW Windows 6

4. Testing in PowerShell and cmd

Open PowerShell or CMD, enter the folder where there is a C/C++ file, compile and run:

gcc/g++ MinGW Windows 7

gcc/g++ MinGW Windows 8

In VS Code it is easier to use:

VS Code

To facilitate the opening of PowerShell in VS Code you can install this extension.


If you wish, you can choose to follow this tutorial to install with MSYS2, however I find it messier, MSYS2 creates a bunch of shortcuts.


See too:

Create Games for Windows, Linux and Web with Raylib C/C++


windows

gcc

cpp

clanguage



Related articles



Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Средство просмотра фотографий вернуть в windows 10 для начинающих
  • Windows уходит с российского рынка
  • Видеоадаптер palit geforce gt 630 драйвер для windows 10
  • Код ошибки 0xc0000221 windows 10 как исправить
  • Powerpoint windows 10 softportal