Mingw64 windows 10 install

While mingw-w64 provides the core Windows headers and libraries needed for
Windows development, it’s not very useful on its own. Most users should install
a pre-built toolchain that combines mingw-w64 with a compiler (like GCC with
binutils, or LLVM/Clang) and other essential build components. These
distributions package everything needed to compile programs for Windows and are
much easier to set up than building from source.

Version Host GCC / mingw-w64 Version Languages Additional Software in Package Manager

Arch
Linux
Rolling Linux 14.2.0/12.0.0 Ada, C, C++, Fortran, Obj-C, Obj-C++ many

Cygwin
Rolling Windows 12.4.0/12.0.0 C, C++, Fortran, Obj-C many


Debian
Debian 10 (Buster) 8.3.0/6.0.0 Ada, C, C++, Fortran, Obj-C, Obj-C++ 9 (gdb, libassuan, libgcrypt, libgpg-error, libksba, libnpth, nsis, win-iconv, zlib)
Debian 11 (Bullseye) 10.2.1/8.0.0
Debian 12 (Bookworm) 12.0.0/10.0.0

Fedora
Fedora 40 14.1.1/11.0.1 Ada, C, C++, Fortran, Obj-C, Obj-C++ many
Fedora 41 14.2.1/12.0.0
LLVM-MinGW 20240518 Windows, Linux, macOS LLVM 18.1.6/trunk C, C++ make, Python

MacPorts
Rolling macOS 14.2.0/12.0.0 C, C++, Fortran, Obj-C, Obj-C++ 1 (nsis)
MinGW-W64-builds Rolling Windows 13.1.0/11.0.0 C, C++, Fortran 4 (gdb, libiconf, python, zlib)

MSYS2
Rolling Windows 14.2.0/trunk Ada, C, C++, Fortran, Obj-C, Obj-C++, OCaml many

Ubuntu
20.04 Focal Fossa 9.3.0/7.0.0 Ada, C, C++, Fortran, Obj-C, Obj-C++ 9 (gdb, libassuan, libgcrypt, libgpg-error, libksba, libnpth, nsis, win-iconv, zlib)
22.04 Jammy Jellyfish 10.3.0/8.0.0
24.04 Noble Numbat 13.2.0/11.0.1
24.10 Oracular Oriole 14.1.0/12.0.0
w64devkit 2.0.0 Windows 14.2.0/12.0.0 C, C++, Fortran 8
(busybox,
cppcheck,
ctags,
gdb,
make,
nasm,
pkg-config,
vim)
WinLibs.com Rolling Windows 13.2.0 Ada, C, C++, Fortran, Obj-C, Obj-C++, Assembler Package manager: work in progress (will offer > 2500 packages)

Arch Linux

Installation:

  • Extra repository (toolchain)
  • AUR repository (additional packages)

Cygwin

Cygwin is a Unix-like environment and command-line
interface for Microsoft Windows. Its core is the cygwin1.dll library which
provides POSIX functionality on top of the Win32 API. It can be used as a build
environment which targets Windows directly and for which output doesn’t depend
on cygwin1.dll.

Installation is done through cygwin’s package manager:
setup.exe.

As part of the numerous packages in cygwin, there are cross-compilation
toolchains which target both 32 bits and 64 bits; their names start with
“mingw64-”.

Once they are installed, they should be used according to the general
cross-compilation approach.

Debian

Installation: through integrated package manager.

mingw-w64 packages on Debian

Fedora

Installation: through integrated package manager.

LLVM-MinGW

LLVM-MinGW is a toolchain built with Clang, LLD, libc++, targeting
i686, x86_64, arm and aarch64 (ARM64), with releases both for running
as a cross compiler from Linux and for running on Windows. It supports
Address Sanitizer, Undefined Behaviour Sanitizer, and generating debug
info in PDB format.

Installation: GitHub

MacPorts

To install just the 32-bit or just 64-bit compiler with dependencies, use:

sudo port install i686-w64-mingw32-gcc
sudo port install x86_64-w64-mingw32-gcc

A shortcut to install both:

sudo port install mingw-w64

Here is the list of mingw-w64 packages on MacPorts.

MinGW-W64-builds

Installation: GitHub

MSYS2

Installation: GitHub

Ubuntu

Installation: through integrated package manager.

mingw-w64 packages on Ubuntu

w64devkit

w64devkit is a portable C and C++ development kit for x64 (and x86) Windows.

Included tools:

  • mingw-w64 GCC : compilers, linker, assembler
  • GDB : debugger
  • GNU Make : standard build tool
  • busybox-w32 : standard unix utilities, including sh
  • Vim : powerful text editor
  • Universal Ctags : source navigation
  • NASM : x86 assembler
  • Cppcheck : static code analysis

The toolchain includes pthreads, C++11 threads, and OpenMP. All included
runtime components are static.

Installation: GitHub

WinLibs.com

Standalone mingw-w64+GCC builds for Windows, built from scratch (including all dependencies) natively on Windows for Windows.

Downloads are archive files (.zip or .7z). No installation is required,
just extract the archive and start using the programs in mingw32\bin or mingw64\bin.
This allows for a relocatable compiler suite and allows having multiple versions on the same system.

Also contains other tools including:

  • GDB — the GNU Project debugger
  • GNU Binutils — a collection of binary tools
  • GNU Make — a tool which controls the generation of executables and other non-source files
  • Yasm — The Yasm Modular Assembler Project
  • NASM — The Netwide Assembler
  • JWasm — A free MASM-compatible assembler

Flavors:

  • separate packages for 32-bit (i686) and 64-bit (x86_64) Windows
  • separate packages for MSVCRT and UCRT builds
  • only POSIX threads builds (which also include Win32 API thread functions)
  • exception model: Dwarf for 32-bit (i686) and SEH for 64-bit (x86_64)

Installation: Download from winlibs.com and extract archive (no installation needed).

Unsorted complementary list

GCC with the MCF thread model

GCC with the MCF thread model is a series of
x86 and x64 native toolchains built by LH_Mouse. The MCF thread model has been
merged into GCC 13, and can be enabled by passing --enable-threads=mcf to
GCC’s configure script. C++11 threading facilities, such as std::thread,
std::mutex, std::condition_variable, std::call_once, thread_local etc.
invoke the mcfgthread library, which
implements them on Windows syscalls in a more standard-compliant and more
efficient way, outperforming even native slim reader/write locks (SRW) since
Windows Vista.

OpenSUSE

The OpenSUSE Linux distribution also has a large and
well-maintained set of packages for cross-compilation.

How to setup C++, Cmake and Make to Work Natively in Windows 10 using MinGW

🚀 End goal: To create the same developer setup as Mac and Linux without having to rely on proprietary Microsoft Visual Studio (MSVC).

Note: You will need to run most commands as an Administrator in the Command Prompt.

1️⃣ Install Chocolately

Official Instructions

Why? We need a package manager

Linux has apt-get by default

sudo apt-get <packageName>

Mac has Homebrew

brew install <packageName>

Windows has Chocolately

choco install <packageName>

2️⃣ Recommend you install Windows Terminal and Powershell (Optional)

Official Windows Terminal Instructions

The default Command Prompt sucks. 💩 It’s like trying to build a house without power tools. We have technology.

Official Powershell Instructions

Set your default shell to Powershell. Don’t use «Powershell Core»… that’s a weird Microsoft project to try to get Linux and Mac users to switch to Powershell.

3️⃣ Install MinGW (GCC and G++ compiler)

MinGW-64 is the Windows equivalent of GCC (for C) and G++ (for C++). It even comes with the gdb debugger! 😍

  1. GCC ➡️ GNU C Compiler
  2. G++ ➡️ GNU C++ Compiler

4️⃣ Install Cmake and Make

Add cmake as a command in your Environment Variables. There is a bug in the installer and it doesn’t automatically create a command alias for you.

  1. Search for Environment Variables in Windows
  2. Click on Environment Variables button
  3. In the upper window (user variables) click on New
  4. Variable name = cmake
  5. Variable path = C:\Program Files\CMake\bin
    • Please verify this path on your own computer
    • You will know this is the correct bin folder if it contains cmake.exe
  6. Click OK and OK to finish

Check that MinGW, Cmake, and Make are installed correctly in the Terminal:

g++ --version
>>  g++.exe (MinGW-W64 x86_64-posix-seh, built by Brecht Sanders) 11.2.0
    Copyright (C) 2021 Free Software Foundation, Inc.

cmake --version
>>  cmake version 3.21.3

make --version
>>  GNU Make 4.3
    Built for Windows32

You can even check that other GNU tools from MinGW are installed:

grep --version
>> grep (GNU grep) 3.0

gdb --version
>> GNU gdb (GDB for MinGW-W64 x86_64, built by Brecht Sanders) 10.2

bash --version
>> GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu)

If you forget where G++ is installed, use this:

which g++
>>  /c/ProgramData/chocolatey/bin/g++

Refresh your Terminal environment variables with refreshenv

5️⃣ Download and Install SFML

SFML Downloads Page

  1. Download GCC 7.3.0 MinGW (SEH) — 64-bit

    • Place this SFML folder somewhere safe like C:\Users\yourname\Documents\. Don’t lose this folder!
    • We don’t want the Visual C++ versions.
    • The 32-bit version should work as well if you want to use that instead.
  2. We do NOT want to manually tell the GCC/G++ compiler where to find our SFML library. Doing this will suck because GCC/G++ and Cmake will not be able to find SFML by itself.

  3. We WANT to add this SFML library as a choco package into our computer.

  4. Use this Github code to help add SFML as a choco package.

    • Download all files from this Github repository: https://github.com/jeanmimib/sfml-mingw64
      git clone https://github.com/jeanmimib/sfml-mingw64.git
      
    • Place this folder into a temporary place like C:\Users\yourname\Documents\. You can delete this folder afterwards.
    • In the terminal, go into this temporary sfml-mingw64 folder.
    • Type this command. It will create a nupkg file.
    • Type this command. It will install SFML as a choco package that MingGW can easily find. The dot means «here», and since you’re in the same folder as the nupkg file, choco will find it.
      choco install sfml-mingw64 -s .
      
  5. Check that all choco packages are installed correctly.

    choco list --local-only
    >>  Chocolatey v0.11.2
        cmake 3.21.3
        cmake.install 3.21.3
        make 4.3
        mingw 11.2.0
        sfml-mingw64 2.5.1  
    

Refresh your Terminal environment variables with refreshenv

6️⃣ Configure your IDE with working IntelliSense

  1. I use Visual Studio Code (VS Code), so you will need to find the equivalent in your IDE.

  2. Open up your VS Code such that the working folder is your desired Project Home.

    • You should see the include and src folders.
    • There are no parent folders above this folder!
  3. Install the C/C++ extension (by Microsoft) because we want all the coding power we can get.

  4. Install the Cmake Tools extension (by Microsoft) if you want. This is optional because we have already installed Cmake into our system. This Cmake extension only works inside VS Code and automatically builds your project when you save your files. This extension does not make an .exe file!

  5. ‼️ Because I have the Cmake tools extension, it generates a /build folder for me which is the same thing as /bin. ‼️

  6. Open up the command palette with ctrl + shift + p.

  7. Select edit configuration (ui) in the search bar.

    edit configuration ui

  8. Change the following configurations:

    Configuration Name Setting
    Compiler Path C:/ProgramData/chocolatey/bin/g++.exe
    IntelliSense mode windows-gcc-x64
    Include Path ${workspaceFolder}/**
    C:\Users\yourname\Documents\SFML-2.5.1\include
    C++ standard C++ 17
  9. Here we have 2 include paths. (1) The project’s include and (2) SFML’s include that you stored in a safe place. If you eventually have more external libraries, add them in «Include Path» as a new line.

  10. Your IDE IntelliSense should now be happy. The red lines should go away because now it can find the .hpp files.

7️⃣ Write your CMakeLists.txt

We are not going to use any absolute file paths. This usually leads to errors because the compiler can’t find stuff.

cmake_minimum_required(VERSION 3.10)

project(
    App             # Name of our application
    VERSION 1.0     # Version of our software
    LANGUAGES CXX)  # Language that we are using

set(CMAKE_CXX_STANDARD 17)

include_directories("./include/")

find_package(SFML 2.5.1 COMPONENTS graphics window system REQUIRED)

add_executable(${PROJECT_NAME} ./src/App.cpp ./src/Draw.cpp ./src/Command.cpp ./src/main.cpp)

target_link_libraries(${PROJECT_NAME} sfml-graphics sfml-window sfml-system)

8️⃣ Link the MinGW64 .dll libraries to your project

There are two ways to link .dll libraries in Windows 10.

Option 1: You want to distribute the .exe program.

If you want to distribute a prebuilt .exe program, you should include the .dll libraries within the program files. Otherwise, a normal user will never be able to find & link the .dll libraries. You either provide all the necessary .dll in one package, or you create a Windows installer (lmao).

  1. Copy/paste all the MinGW .dll files into your project /bin or /build folder which contains the prebuilt .exe program.

  2. For example, my .dll file location is: C:\ProgramData\chocolatey\lib\mingw\tools\install\mingw64\bin.

  3. Use the search bar to filter by .dll and copy all.

    dll files

  4. Paste .dll files

Option 2: You want to build the .exe program as a developer.

If you are a developer, you should let your computer automatically find the necessary .dll so that you don’t have to copy/paste .dll every time to work on a new project.

  1. Add the folder containing all the .dll libraries into your system PATH variable.

  2. Go into Environment Variables again. Edit the Path variable.

    env-variables

  3. Add the location for MinGW64 .dll folder into your PATH variable. For example, my location is: C:\ProgramData\chocolatey\lib\mingw\tools\install\mingw64\bin.

    new-path

9️⃣ Build your Project

  • Go into your project /bin or /build folder in the Terminal
  • Type cmake -G "MinGW Makefiles .. in the Terminal
  • This will generate the makefiles for the MinGW compiler
  • Type make in the Terminal
  • This will build your executible
  • Pray that it works 🙏
  • Try running the App.exe
  • Extra Notes:
    • It is good practice to build outside of your source directory. This is why we tell cmake to target one directory up (..)
    • After you run cmake -G "MinGW Makefiles .. one time, cmake will remember that you are using MinGW. So the next time you re-compile, you can just type cmake ..
    • If you ever delete your makefiles, you will need to re-generate them
  • VSCode Notes:
    • The VSCode cmake extension can auto generate the makefiles for you if you set it up correctly in the configuration (see step 6 above). It generates each time you hit save.

🎬 Demo of Native Windows Build

https://streamable.com/jaevms

Help! It doesn’t work

  • Restart your computer. Seriously, try it.
  • Delete the VSCode settings (in the folder called .vscode), restart VSCode, and re-apply the settings.
  • Windows is stubborn, so restart anything you can think of.

Для работы над заданиями курса в Windows 10 рекомендуется использовать следующее программное окружение:

  • Редактор Visual Studio Code
  • Инструменты командной строки Git for Windows
  • Среда разработки MinGW-w64 (Minimalist GNU for Windows), содержащая компилятор GCC (GNU Compiler Collection)
  • Инструменты для сборки проектов CMake
  • Система управления пакетами python Miniconda3

Рассмотрим процесс установки и настройки этих инструментов.

Установка VS Code

Установка VS Code не представляет сложностей. Достаточно скачать установочный файл со страницы загрузок и запустить его. Пока это все, что необходимо сделать. После установки остальных программ мы вернемся к настройке VS Code.

Установка и настройка Git for Windows

Скачайте установочный файл Git for Windows со страницы загрузок и запустите его. На момент написания этого текста актуальной версией является 2.28.0. В процессе установки Вам будут заданы вопросы по конфигурации. В большинстве случаев подойдут рекомендуемые варианты.

Если в системе уже установлен редактор VS Code, то его можно выбрать в качестве редактора по умолчанию для Git:

git-setup-default-editor

Важным моментом является настройка обработки конца строки в файлах. Чтобы с этим не возникало проблем, необходимо выбрать вариант, который уже отмечен по умолчанию:

git-setup-line-ending

Чтобы команды git были доступны во всех терминалах, следует выбрать рекомендуемый вариант для изменения переменной окружения PATH:

git-setup-PATH

Проверьте, что установка завершилась успешно, открыв терминал и исполнив команду git. Результат должен выглядеть так:

> git
usage: git [--version] [--help] [-C <path>] [-c <name>=<value>]
           [--exec-path[=<path>]] [--html-path] [--man-path]
           [--info-path] [-p | --paginate | -P | --no-pager]
           [--no-replace-objects] [--bare] [--git-dir=<path>]
           [--work-tree=<path>] [--namespace=<name>]
           <command> [<args>]

В качестве терминала в Windows 10 мы рекомендуем использовать PowerShell.

Теперь необходимо задать имя пользователя и адрес электронной почты:

> git config --global user.name "Ivan Petrov"
> git config --global user.email i.petrov@nsu.ru

Git хранит настройки в файле ~\.gitconfig. У автора этот файл выглядит следующим образом:

[user]
    email = vit.vorobiev@gmail.com
    name = Vitaly Vorobyev
[core]
    editor = \"[path-to-vscode]" --wait

На этом первоначальная конфигурация инструментов git завершена. Навык работы с git приходит с практикой. Действия с git, необходимые для выполнения заданий курса, всегда будут подробно описаны. Тем не менее, мы рекомендуем обращаться к документации, чтобы прояснять непонятные моменты.

Установка MinGW-w64

Установочный файл MinGW-w64 mingw-w64-install.exe можно найти на этой странице. При установке не нужно менять настройки по умолчанию, кроме пути установки. Путь установки не должен содержать пробелов, поэтому путь по умолчанию в директории Program Files не подходит.

После завершения установки, в директории mingw32\bin будут расположены различные исполняемые файлы. Среди них нас интересует файл g++.exe, который запускает сборку программ C++. Сделаем так, чтобы этот файл был доступен в любой директории из командной строки. Если этого не сделать, то для использования команды g++ надо будет прописывать полный путь до файла g++.exe.

Откройте меню “Система” в “Панели управления”:

mingw-path-1

Из меню “Система” перейдите в “Дополнительные параметры системы”:

mingw-path-2

Выберите “Переменные среды”:

mingw-path-3

Выберите переменную Path и нажмите кнопку “Изменить…”:

mingw-path-4

Добавьте в новую строку полный путь до директории mingw32\bin и нажмите кнопку OK.

mingw-path-5

Чтобы проверить, что настройка выполнена успешно, откройте консоль (не в директории mingw32\bin) и выполните команду g++ --help:

> g++ --help
Usage: g++.exe [options] file...

Ваша система теперь готова к сборке программ на языке C++.

Установка CMake

Скачайте со станицы загрузок установочный файл cmake-3.18.1-win64-x64.msi (на момент написания текста актуальная версия — 3.18.1). Для 32-разрядной системы вместо этого нужно скачать файл cmake-3.18.1-win32-x86.msi. Запустите файл и выполните установку. В ходе установки выберите изменение переменной окружения PATH:

cmake-path

Выполните в консоли команду cmake --help для проверки корректности установки CMake:

> cmake --help
Usage

  cmake [options] <path-to-source>
  cmake [options] <path-to-existing-build>
  cmake [options] -S <path-to-source> -B <path-to-build>

Specify a source directory to (re-)generate a build system for it in 
the current working directory.  Specify an existing build directory to
re-generate its build system.

Код большинства заданий по C++ этого курса будет компилироваться с помощью CMake. Эта система значительно упрощает процесс сборки C++ проектов, особенно если они состоят из многих файлов.

Установка Miniconda3

Система Windows (в отличие от Linux) не имеет установленного по умолчанию интерпретатора python. Менеджер пакетов python Anaconda и его минимальная сборка Miniconda позволят нам установить в системы все необходимые инструменты для работы с python. Загрузите со страницы загрузки установочный файл Miniconda3 Windows 64-bit или Miniconda3 Windows 32-bit, в зависимости от разрядности системы. При установке отметьте галочку для добавления необходимых записей в переменную окружения PATH, несмотря на то что это действие не рекомендуется установщиком:

miniconda-path

Убедитесь в том, что установка выполнена успешно, выполнив в консоли следующую команду:

>conda --help
usage: conda-script.py [-h] [-V] command ...

conda is a tool for managing and deploying applications, environments and packages.

Выполните инициализацию (необходимо выполнить один раз):

Создайте окружение для работы с заданиями этого курса:

>conda create -n nsu python=3

Conda вычислит набор пакетов, которые необходимо установить в новом окружении, и попросит подтвердить создание окружения:

После установки активируйте новое окружение и запустите консоль python:

>conda activate nsu
(nsu) >python
Python 3.8.5 (default, Aug  5 2020, 09:44:06) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Ваша система теперь готова для работы с заданиями курса “Программирование на C++ и python”. Нам осталось настроить редактор VS Code для максимально удобной работы.

Настройка VS Code

Установите следующие расширения VS Code:

  • C/C++ for Visual Studio Code
  • CMake Tools
  • Python

Выбор интерпретатора python

При начале работы с кодом python (при открытии файла с расширением .py) VS Code предложит выбрать интерпретатор python, который будет использоваться для подсветки кода, проверки синтаксиса и вывода подсказок:

vscode-python-interpreter

Можете, например, выбрать интерпретатор из недавно созданного окружения nsu.

Создадим файл test.py, содержащий одну строку:

Исполнить этот скрипт можно, открыв консоль в VS Code с помощью сочетания клавиш Ctrl+J и набрав в ней

В правом верхнем углу окна находится кнопка с зеленым треугольником ▷, нажатие на которую приводит к тому же результату:

vscode-python-hello-world

Настройка работы с GCC

Создайте файл test.cpp, содержащий следующий код:

#include <iostream>

int main() {
    std::cout << "Hello, world!" << std::endl;
    return 0;
}

Скомпилируем его с помощью компилятора GCC и командной строки. Откройте консоль в VS Code (Ctrl+J) и исполните команду

Компилятор создал исполняемый файл a.exe. Запустите его:

Работает. Настроим теперь VS Code для автоматизации этого действия. Выберите в меню пункт Terminal -> Configure Default Build Task...:

vscode-cpp-default-build-task

Выберите из выпавшего списка пункт g++.exe. В результате будет сгенерирован файл .vscode/tasks.json подобный такому:

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "C/C++: cpp.exe build active file",
            "command": "D:\\mingw\\mingw32\\bin\\g++.exe",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "${workspaceFolder}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Теперь при нажатии клавиш Ctrl+Shift+B или выборе пункта меню Terminal -> Run Build Task будет выполняться компиляция открытого файла. Для файла test.cpp будет создан исполняемый файл test.exe.

Работа с CMake

Откройте новую рабочую директорию VS Code, создайте в ней файл main.cpp, содержащий следующий код:

#include <iostream>

int main() {
    std::cout << "Hello, world!" << std::endl;
    return 0;
}

и файл CMakeLists.txt со следующим содержанием:

cmake_minimum_required(VERSION 3.0.0)
add_executable(test main.cpp)

Эти два файла составляют минимальный CMake-проект. Выполним сначала сборку CMake-проекта через консоль: создайте в рабочей директории поддиректорию build, в которой будет осуществляться сборка, и перейдите в неё:

Выполните настройку проекта и запустите сборку:

> cmake -G "MinGW Makefiles" ..
> cmake --build .

В первой команде мы указали, что сборка будет осуществляться с помощью MinGW и что файлы проекта расположены в родительской директории (путь ..). Вторая команда осуществляет сборку в текущей директории (путь .). В директории build должен появиться исполняемый файл test.exe.

Расширение VS Code для работы с CMake позволяет автоматизировать сборку проекта. Выберите рабочую директорию VS Code (комбинация клавиш Ctrl+K+O), содержащую файлы main.cpp и CMakeLists.txt. Наберите комбинацию клавиш Ctrl+Shift+P и в строке сверху наберите команду >CMake: Configure. Это запустит настройку инструментов CMake. После завершения настройки в нижней части окна появятся инструменты управления сборкой:

cmake-example-project

Кнопку “Сборка” запускает сборку, а кнопка ▷ — исполняемый файл.

Если автоматическая настройка CMake привела к ошибке, то, вероятно, инициализация CMake выполнилась без параметра -G "MinGW Makefiles". В этом случае выполните эту команду в консоли, как показано выше. Достаточно выполнить это действие один раз, после чего конфигурация этого и других проектов будет выполняться верно.

Работа с git

Покажем как можно работать с git-репозиторием через VS Code. Выполните fork репозитория задания Hello, Classroom на GitHub:

github-fork

Это действие создает новый репозиторий в Вашем аккаунте. Разрешите автоматическое тестирование решения, нажав на большую зеленую кнопку во вкладке Actions:

github-actions

Новый репозиторий необходимо клонировать на Вашу локальную систему. Удобнее всего это делать с помощью протокола ssh. Для этого сначала необходимо включить OpenSSH Client, который по умолчанию выключен.

Взаимодействие с GitHub репозиторием будет происходить по протоколу ssh с помощью техники шифрования с открытым ключом. Создать пару из приватного и публичного ключа можно в консоли:

>ssh-keygen
Generating public/private rsa key pair.

По умолчанию сгенерированные ключи будут расположены в директории ~\.ssh. Файл с публичным ключом называется id-rsa.pub. Публичный ключ нужно добавить на GitHub. Для этого откройте раздел SSH and GPG keys в меню Settings и нажмите на кнопку New SSH key:

github-ssh-key

Заполните открывшуюся форму. В поле Key нужно скопировать содержимое файла id-rsa.pub. Проследите, чтобы при копировании не появились лишние переносы строк. Весь ключ должен быть расположен в одной строке.

Теперь мы готовы к клонированию репозитория. Выберите на компьютере директорию, в которой Вы будете работать с заданиями курса и перейдите в неё. Откройте страницу репозитория hello-classroom в Вашем аккаунте GitHub и скопируйте строку для клонирования через ssh:

github-clone

Выполните в консоли команду git clone:

> git clone git@github.com:fakestud/hello-classroom.git
Cloning into 'hello-classroom'...
remote: Enumerating objects: 15, done.
remote: Counting objects: 100% (15/15), done.
remote: Compressing objects: 100% (8/8), done.
remote: Total 15 (delta 0), reused 15 (delta 0), pack-reused 0
Receiving objects: 100% (15/15), done

Строка git@github.com:fakestud/hello-classroom.git есть скопированная выше строка. Репозиторий был клонирован в директорию hello-classroom. Выберите её в качестве рабочей директории VS Code. Прочитайте файл README.md, содержащий инструкции по решению задания. После решения задания выполните локальную проверку:

> conda activate nsu
> pip install -r .\requirements.txt
> g++ -std=c++17 main.cpp -o a.out
> test_cmd tests/ .\a.out
Running 1 tests on 4 CPUs...

test1
Command: .\a.out
Success

All 1 tests passed.

Тесты пройдены успешны. Значит, мы готовы к синхронизации репозитория GitHub с нашей локальной версией. В командной строке для этого достаточно выполнить следующие команды:

git add main.cpp
git commit -m "Task solved"
git push -u origin master

Редактор VS Code позволяет выполнить эти действия через графический интерфейс. VS Code отслеживает изменения локальной версии репозитория. Откройте вкладку контроля версий слева и посмотрите на список изменившихся файлов. В нашем случае это должен быть только файл main.cpp. Выполните команду git add, нажав на кнопку +:

Затем команду git commit, нажав на кнопку ✓ и введя комментарий в текстовом поле:

vscode-git-commit

Наконец, выполните команду git push:

Источники

  • First-Time Git Setup
  • VS Code: User and Workspace Settings
  • VS Code: Using GCC with MinGW
  • VS Code: Get started with CMake Tools on Linux
  • Git in Visual Studio Code
  • Must-have плагины и несколько полезностей для С\С++ разработки в VS Code
  • Памятка пользователям ssh

MinGW (Mingw-64) Download for Windows 11 64-bit - #1 GCC Compiler for PC

MinGW in recent times was known as MinGW32 and a newer version as MinGW-w64. It is an open-source development software that you can use to create Microsoft Windows Apps. The developers of the project have written it in C and C++. The main reason to use MinGW Download is to develop and support GCC which is a collection of programming languages compiler of Windows 11/10.

Some call it as GNU Compiler Collection. Its native Windows port carries extensions to Microsoft Visual C++ (Microsoft Visual C++) runtime, which shall support the C99 function. For those who do not know this is an older version of the C language standard. You can execute all software which are created through MinGW on 64-bit Windows platform.

What is MinGW

Use this to compile system that are based on GNU, GCC and Binutils project and both compile and links the codes that need to run on all the Win32 systems. Moreover, it shall also provide you with compilers for Fortan, C and C++. The best thing is it is not dependent upon third-party C runtime DLL files but inside the program, it comes with Jargon which can be a bit overwhelming.

MinGW-w64 Free Download for Windows 11

MinGW stands for Minimalist GNU for Windows. It does not give you any POSIX runtime environment for the POSIX app deployment. If you wan this then you need to use Cygwin instead. It shall also provide you with each and every open-source programming tool set that is required in developing Windows applications. After reading all this, yes, you are thinking right this is perfect for easy yet intuitive installation of GNU compiler collections. You can also use C or C++ IDEs if you intend to make applications in general but for native support, MinGW is unbeatable.

MinGW Newest Features

There are features released now and again by the project team and some notable ones include:

  1. API document in API format.
  2. GNU compiler collection port which is GCC including C, C++, ADA and Fortran compilers.
  3. A utility, gdbmigrator() which shall provide you with automated migration of code written against Microsoft.
  4. GNU Binutils for Windows 11 like linker, archive manager, assembler and much more.
  5. Command line installation, mingw-get in order to obtain and manage its installation packages.

Advantages and Disadvantages of using MinGW

This is not a great option if you are new to programming and willing to learn. Go for PowerShell which comes for free. As MinGW is easy to use the downloads are all over the place and there are many other types of downloads on top of one another. The auto-installer also does not work properly. Moreover, it also comes with errors while you update them from your sync repositories.

Download MinGW GCC Compiler Latest Version

For more ease, you can check the web for some tutorials on how to install and use the program. Keep in mind that many of these are conflicting. Even on official sites, you shall see that many links are broken so it gets all confusing. All this is because the project has not been well-maintained by the developers so it’s outdated but still it is great to build native Windows applications.

It is outdated. If you intend to use scripts natively and uniquely on Windows, then this is a useful program. With this, you can easily search Windows files in UNIX manner through its find command. At the same time, you can also find out many issues when it comes to the process of installation. At times you need to do it manually.

ALSO SEE: 6 Best Free Python Compilers for Beginners.

How To Install MinGW on Windows 11 (A step-by-step process)

Once the installer has been downloaded you need to follow the steps mentioned below:

  1. You need to head to the folder which carries MinGW-64 installer (mingw-w64-Windows-11-10-exe).
  2. Once done, run the installer and hit “next” on the steps presented.
  3. You need to select the following for the compiler to work correctly.
    Mingw64 Download for Windows PC

  4. After this change, the destination folder to C:\mingw make sure to not put any space in the name of the folder ever.
  5. The installer at this point shall download the necessary files. Once done, they shall be in the location where you have specified above.
  6. Now the installer shall extract files from the downloaded file and place them into the installation directory.
  7. A dialog shall pop up once all the files have been installed, hit “next”.
  8. If the installation process was a hit then you shall see a final dialog box, hit “finish” to complete.
  9. Now the last one is a hard step for many students mainly because they did not properly configure their system after the software was installed.

If you want to use gcc or g++ compilers for any command prompt then you need to add the location of “bin” folder to the path, assuming you have installed MinGW in C:\mingw as mentioned above you need to add the following:

Paul@ninja-ide:~# \Paul\mingw\mingw64\bin

In the start, if you are not aware on how to modify the path then you take help.

When adding \Paul\mingw\mingw64\bin to the path this needs to be the first entry in the path, otherwise, it shall cause the wrong compilers to be used. Once this is done you need to logout and login to Windows.

As you log-in again you need to open a command prompt, at this time you shall be able to type “gcc” from any command window and get the latest version of the compilers.

How To Install MinGW Tools for C/C++ in Windows 11

If you are planning to code in C or C++ in MinGW then having MinGW Tools installed is a must.

  1. You need to check “MSYS Basic System” at the select component dialog.
  2. Add Paul\MinGW\bin folder to Windows path variable, for click right on the computer and choose “properties” > click on “advanced system settings”, select “the advanced tab”, hit “environment variables” > under system variables, go down and choose “path” then hit “edit” > carefully go to the right of the variable value field and make sure to not delete anything > at end of field include a semicolon. This process is almost identical to when you are adding an environment Path for Python to work on Windows 11.
  3. You need to verify that the install was successful for this: go to “start” and type “cmd” in the search field and hit “enter” > enter gcc in the terminal which appears and hit “enter”.
  4. Done, this will show you that MinGW is now properly working.

How to Fix (The File has been Downloaded Incorrectly) Error in MinGW

If you have just downloaded MingGW and were trying to install it but the above error struck you then follow the 5 steps below to fix it:

  1. You need to download the “MinGW-w64 zip file”.
  2. After this unzip the files and copy them to Paul\mingw64.
  3. Then add this to Environment Variables in Windows 11 or 10.

It does not depend upon Microsoft C-Runtime DLLS, so it is possible to compile and link apps with it without additional libraries. When used in conjunction with SDSS which is a small device C compiler then you can develop efficient embedded systems app targeting huge range of devices.

Related posts you may like:

  • Download Dev-C++ Free for PC in 64-bit.
  • Atom Editor For Windows 11 Download.
  • Code::Blocks Download for Windows 11.

MinGW is your go-to software if you are a developer creating apps for Windows. MinGW Download for Windows 11 in 64-bit allows you to create apps that will work natively on any PC. MinGW-64 is the same however it was improved and came with more libraries for native programming.

Title Information
Name: Standard: MinGW
Improved: MinGW-w64
License: Free (General Public License)
OS Support: Windows 10 and Windows 11
Author: Colin Peters
Version: 10.0 (Latest)
Size: 15.6 MB for Zip Archive
85 KB for Installer

MinGW Free Download

How to install 64 bit (GCC) GNU Compiler Collection (Mingw-w64 port) on a Windows 10 system using MSYS2 installer for C/C++ software development.

In this tutorial ,We will learn How to install 64 bit (GCC) GNU Compiler Collection (Mingw-w64 port) on a Windows 10 system using MSYS2 installer for C/C++ software development.

Contents

  • GCC on Windows Platform 
  • What is Mingw-w64 
  • What is MSYS2 
    • Installing MSYS2 on Windows 
    • Install GCC on Windows using Pacman on Windows 10 
  • Compiling C/C++ file on Windows-10 using GCC (MingW-w64/MSYS2) 
    • Compiling a C file using GCC (MingW-w64/MSYS2) 
    • Compiling a C++ code using GCC (MingW-w64/MSYS2)
    • Compiling a Win32/64 API GUI C code using GCC 
  • IDE’s for C/C++ development on Windows

GCC on Windows Platform

GNU Compiler Collection (GCC) is an compiler produced by the GNU Project supporting various programming languages like for Objective-C, Objective-C++, Fortran, Ada, D and Go. Here we will be concentrating only C/C++ development on Windows 10.

GCC along with other utilities like  GNU Binutils for Windows (assembler, linker, archive manager),  set of freely distributable Windows specific header files and static import libraries have been ported to Windows platform and is available in the following flavors.

  1. MinGW —  («Minimalist GNU for Windows») which can be used for creating 32 bit native executable on Windows platform
  2. Mingw-w64 — 64bit version

Please note that we will not be covering WSL or Windows Subsystem for Linux.

learn how to install Mingw-w64 on Windows 10 tutorial

What is Mingw-w64 

Mingw-w64  is a fork off MinGW which provides a more complete Win32 API implementation including Win64 support,C99 support, DDK, DirectX.Mingw-w64 can generate 32 bit and 64-bit executables for x86 under the target names i686-w64-mingw32 and x86_64-w64-mingw32.

Here we will be using Mingw-w64 for C/C++ native application development using Windows API as most modern PC are now 64 bit.

Mingw-w64 Project does not provide any binaries for download from its website instead it maintains a list of Pre-built toolchains and packages provided by other vendors.

These  prebuilt toolchains contains GCC, Debugger ,Package Manager ,Terminals and a set of other Unix tools like curl, openssl, sed, awk etc which can be used for development on Windows Platform.

available prebuilt tutorials of 64 bit mingw-w64 gcc ports for windows 10

Here we will be using a Mingw-w64 package called MSYS2 Software Distribution 

What is MSYS2 

MSYS2 is a collection of tools and libraries providing the developer with an easy-to-use environment for building, installing and running native Windows software. 

MSYS2 Software Distribution consists of

  • command line terminal called mintty,  
  • Bash,
  • tools like tar and awk  
  • build systems like autotools,  

all based on a modified version of Cygwin. Despite some of these central parts being based on Cygwin, the main focus of MSYS2 is to provide a build environment for native Windows software and the Cygwin-using parts are kept at a minimum.

To install and remove various software packages internally  MSYS2 uses Pacman as their package manager.

MSYS2 is sponsored by Microsoft Open Source Programs Office through their  FOSS Fund.

  • Download MSYS2 Software Distribution (Mingw-w64) for Windows

  • Download extra MSYS2 Packages from Repo here     
     

Installing MSYS2 on Windows

Installing MSYS2 on Windows 10 is quite easy. Download the executable using the above link and run it.

After the binary is installed on your system ,

MSYS2 comes with different environments/subsystems and the first thing you have to decide is which one to use.

The differences among the environments are mainly environment variables, default compilers/linkers, architecture, system libraries used etc.

If you are unsure, go with UCRT64.

UCRT (Universal C Runtime) is a newer version which is also used by Microsoft Visual Studio by default.    
It should work and behave as if the code was compiled with MSVC.

mintty terminal of msys2

You can start a terminal .The default terminal is Mintty (above)

Install GCC on Windows using Pacman on Windows 10

MSYS2 on Windows 10 uses pacman as its package manager.After installing MSYS2 ,you can check the installed packages by typing

$pacman -Q 

on the Mintty terminal. This will list all the available packages on your system as shown below.

GCC will not be installed by default, So you can go to the package repo and search for gcc.

installing gcc Mingw-w64 from msys2 repo on windows 10 using pacman

You can now use pacman to install gcc on Windows.

$pacman -S gcc

Installation process of GCC using pacman on Windows 10 (below)

 installing gcc Mingw-w64 from msys2 repo on windows 10 using pacman

After which you can check GCC by issuing the whereis command.

$whereis gcc

checking whether gcc is installed on windows using pacman and mingw-w64

Compiling C/C++ file on Windows-10 using GCC (MingW-w64/MSYS2)

Once we have installed the Compiler, we will compile a hello world C and C++ code using the installed GCC on Windows 10.

Compiling a C file using GCC (MingW-w64/MSYS2)

Type the below simple code on a text editor like notepad.exe or other text editors like Sublime Text,Notepad++

Save the below C Code as main_c.c

#include<stdio.h>
int main()
{
 printf("Hello World");
 return 0;
}

Compile and run the code using the below commands

$ gcc -o main_c main_c.c
$ ./main_c

Compiling a C++ code using GCC (MingW-w64/MSYS2) using g++

Here we will be compiling a simple C++ file using the g++ compiler in the MSYS2 (MingW-w64) tool chain. 

Save the C++ Code as  main_cpp.cpp

#include <iostream>
using namespace std;
int main()
{
   cout << "Hello from MSYS2\n!";
   cout << "Compiled C++ File\n!";
}

Compile and run the C++ code using g++ compiler as shown below.

$ g++ -o main_cpp main_cpp.cpp
$ ./main_cpp

Compiling a Win32/64 API GUI C code using GCC (MingW-w64/MSYS2)

Now we will compile a Win32/64 GUI application using GCC (MingW-w64/MSYS2) on Windows 10 .

We will create a Window and a Message Box using Win32 native api and configure the gcc to compile and link to the native system API.

Copy the below code and save it as win.c

#include<Windows.h>
int WINAPI WinMain(  HINSTANCE hInstance,     //the instance of the program        
                     HINSTANCE hPrevInstance, //the previous instance 
                     LPSTR lpCmdLine,         //ptr to command line args
                     int nCmdShow)            //display properties
{
   HWND h;     
   h = CreateWindow("BUTTON",
                     "Hit me",
                      WS_OVERLAPPEDWINDOW,
                      350,300,250,100,0,0,
                       hInstance,0); //Create a window with BUTTON class
    
    ShowWindow(h,nCmdShow);   //show the window                                                
    MessageBox(0,"Press Me","Waiting",MB_OK); //used to display window                                                 
}

You can compile the Win32 API code on GCC using the following command

$ gcc -o win  win.c -Wl,--subsystem,windows  -lgdi32
$ ./win

Here

  • The -Wl,—subsystem,windows linker switch ensures that the application is built as a Windows GUI application, and not a console application. Failing to do so would result in a console window being displayed whilst your application runs

  • You should link with the gdi32 library using «-lgdi32 » otherwise the code will complain about «undefined reference to GetStockObject«.

learn how to compile win32 API gui code using GCC (MingW-w64)and MSYS2

Light weight IDE’s for C/C++ development on Windows.

The above examples were all done on command line, Now if you want a full featured opensource C/C++ IDE for development on Windows ,you can check the below list.

  • Code::Blocks IDE 

    • Code::Blocks is a free C/C++ and Fortran IDE that is designed to be very extensible and fully configurable. Built around a plugin framework, Code::Blocks can be extended with plugins.

    •  Code blocks IDE works straight out of box and has a version that comes with  GCC compiler bundled with it. 

    • Documentation of the IDE is also quite Good. 

    • It is a light weight IDE that taxes your system very little.

  • Code Lite IDE

    • CodeLite is an open source, free, cross platform IDE, specialized in C, C++, Rust, Python, PHP and JavaScript (mainly for backend developers using Node.js) programming languages which runs best on all major Platforms ( OSX, Windows and Linux ).

    •  Documentation not that good. 

    • Setting it up was not that easy

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows server 2019 standard управление пользователями
  • Как вызвать автозагрузку в windows 10
  • Windows 10 pro x32 rus загрузочная флешка
  • Как открыть вебкамеру на windows 7
  • Обои windows 10 green