Как добавить mingw в path windows

In this tutorial, you configure Visual Studio Code to use the GCC C++ compiler (g++) and GDB debugger from mingw-w64 to create programs that run on Windows. After configuring VS Code, you will compile, run, and debug a Hello World program.

This tutorial does not teach you about GCC, GDB, minGW-w64, or the C++ language. For those subjects, there are many good resources available on the Web.

If you have any problems, feel free to file an issue for this tutorial in the VS Code documentation repository.

Prerequisites

To successfully complete this tutorial, you must do the following steps:

  1. Install Visual Studio Code.

  2. Install the C/C++ extension for VS Code. You can install the C/C++ extension by searching for ‘C++’ in the Extensions view (⇧⌘X (Windows, Linux Ctrl+Shift+X)).

    C/C++ extension

Get the latest version of MinGW-w64 via MSYS2, which provides up-to-date native builds of GCC, MinGW-w64, and other helpful C++ tools and libraries. This will provide you with the necessary tools to compile your code, debug it, and configure it to work with IntelliSense.

To install the MinGW-w64 toolchain, check out this video or follow the steps below:

  1. You can download the latest installer from the MSYS2 page or use this direct link to the installer.

  2. Run the installer and follow the steps of the installation wizard. Note that MSYS2 requires 64 bit Windows 8.1 or newer.

  3. In the wizard, choose your desired Installation Folder. Record this directory for later. In most cases, the recommended directory is acceptable. The same applies when you get to setting the start menu shortcuts step. When complete, ensure the Run MSYS2 now box is checked and select Finish. This will open a MSYS2 terminal window for you.

  4. In this terminal, install the MinGW-w64 toolchain by running the following command:

    pacman -S --needed base-devel mingw-w64-ucrt-x86_64-toolchain
    
  5. Accept the default number of packages in the toolchain group by pressing Enter.

    MYSS2 Installer

  6. Enter Y when prompted whether to proceed with the installation.

  7. Add the path of your MinGW-w64 bin folder to the Windows PATH environment variable by using the following steps:

    1. In the Windows search bar, type Settings to open your Windows Settings.
    2. Search for Edit environment variables for your account.
    3. In your User variables, select the Path variable and then select Edit.
    4. Select New and add the MinGW-w64 destination folder you recorded during the installation process to the list. If you used the default settings above, then this will be the path: C:\msys64\ucrt64\bin.
    5. Select OK, and then select OK again in the Environment Variables window to update the PATH environment variable.
      You have to reopen any console windows for the updated PATH environment variable to be available.

Check your MinGW installation

To check that your MinGW-w64 tools are correctly installed and available, open a new Command Prompt and type:

gcc --version
g++ --version
gdb --version

You should see output that states which versions of GCC, g++ and GDB you have installed. If this is not the case:

  1. Make sure your PATH variable entry matches the MinGW-w64 binary location where the toolchain was installed. If the compilers do not exist at that PATH entry, make sure you followed the previous instructions.
  2. If gcc has the correct output but not gdb, then you need to install the packages you are missing from the MinGW-w64 toolset.
    • If on compilation you are getting the «The value of miDebuggerPath is invalid.» message, one cause can be you are missing the mingw-w64-gdb package.

Create a Hello World app

First, lets get a project set up.

  1. Launch a Windows command prompt (Enter Windows command prompt in the Windows search bar).
  2. Run the following commands. These will create an empty folder called projects where you can place all your VS Code projects. There, the next commands will create and navigate to a subfolder called helloworld. From there, you will open helloworld directly in VS Code.
mkdir projects
cd projects
mkdir helloworld
cd helloworld
code .

The «code .» command opens VS Code in the current working folder, which becomes your «workspace». Accept the Workspace Trust dialog by selecting Yes, I trust the authors since this is a folder you created.

As you go through the tutorial, you will see three files created in a .vscode folder in the workspace:

  • tasks.json (build instructions)
  • launch.json (debugger settings)
  • c_cpp_properties.json (compiler path and IntelliSense settings)

Add a Hello World source code file

In the File Explorer title bar, select the New File button and name the file helloworld.cpp.

New File title bar button

Add hello world source code

Now paste in this source code:

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    vector<string> msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};

    for (const string& word : msg)
    {
        cout << word << " ";
    }
    cout << endl;
}

Now press ⌘S (Windows, Linux Ctrl+S) to save the file. Notice how the file you just added appears in the File Explorer view (⇧⌘E (Windows, Linux Ctrl+Shift+E)) in the side bar of VS Code:

File Explorer

You can also enable Auto Save to automatically save your file changes, by selecting File > Auto Save. You can find out more about the other views in the VS Code User Interface documentation.

Note: When you save or open a C++ file, you may see a notification from the C/C++ extension about the availability of an Insiders version, which lets you test new features and fixes. You can ignore this notification by selecting the X (Clear Notification).

Explore IntelliSense

IntelliSense is a tool to help you code faster and more efficiently by adding code editing features such as code completion, parameter info, quick info, and member lists.

To see IntelliSense in action,
hover over vector or string to see their type information. If you type msg. in line 10, you can see a completion list of recommended member functions to call, all generated by IntelliSense:

Statement completion IntelliSense

You can press the Tab key to insert a selected member. If you then add open parenthesis, IntelliSense will show information on which arguments are required.

If IntelliSense is not already configured, open the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)) and enter Select IntelliSense Configuration. From the dropdown of compilers, select Use gcc.exe to configure. More information can be found in the IntelliSense configuration documentation.

Run helloworld.cpp

Remember, the C++ extension uses the C++ compiler you have installed on your machine to build your program. Make sure you have completed the «Installing the MinGW-w64 toolchain» step before attempting to run and debug helloworld.cpp in VS Code.

  1. Open helloworld.cpp so that it is the active file.

  2. Press the play button in the top right corner of the editor.

    Screenshot of helloworld.cpp and play button

  3. Choose C/C++: g++.exe build and debug active file from the list of detected compilers on your system.

    C++ debug configuration dropdown

You’ll only be asked to choose a compiler the first time you run helloworld.cpp. This compiler will be set as the «default» compiler in tasks.json file.

  1. After the build succeeds, your program’s output will appear in the integrated Terminal.

    screenshot of program output

Congratulations! You’ve just run your first C++ program in VS Code!

Understanding tasks.json

The first time you run your program, the C++ extension creates a tasks.json file, which you’ll find in your project’s .vscode folder. tasks.json stores your build configurations.

Your new tasks.json file should look similar to the JSON below:

{
  "tasks": [
    {
      "type": "cppbuild",
      "label": "C/C++: g++.exe build active file",
      "command": "C:\\msys64\\ucrt64\\bin\\g++.exe",
      "args": [
        "-fdiagnostics-color=always",
        "-g",
        "${file}",
        "-o",
        "${fileDirname}\\${fileBasenameNoExtension}.exe"
      ],
      "options": {
        "cwd": "${fileDirname}"
      },
      "problemMatcher": ["$gcc"],
      "group": {
        "kind": "build",
        "isDefault": true
      },
      "detail": "Task generated by Debugger."
    }
  ],
  "version": "2.0.0"
}

Note: You can learn more about tasks.json variables in the variables reference.

The command setting specifies the program to run; in this case that is g++.

The args array specifies the command-line arguments passed to g++. These arguments are listed in this file in the specific order expected by the compiler.

This task tells g++ to take the active file (${file}), compile it, and create an output file (-o switch) in the current directory (${fileDirname}) with the same name as the active file but with the .exe extension (${fileBasenameNoExtension}.exe). For us, this results in helloworld.exe.

The label value is what you will see in the tasks list; you can name this whatever you like.

The detail value is what you will see as the description of the task in the tasks list. It’s highly recommended to rename this value to differentiate it from similar tasks.

The problemMatcher value selects the output parser to use for finding errors and warnings in the compiler output. For GCC, you’ll get the best results if you use the $gcc problem matcher.

From now on, the play button will read from tasks.json to figure out how to build and run your program. You can define multiple build tasks in tasks.json, and whichever task is marked as the default will be used by the play button. In case you need to change the default compiler, you can run Tasks: Configure Default Build Task in the Command Palette. Alternatively you can modify the tasks.json file and remove the default by replacing this segment:

    "group": {
        "kind": "build",
        "isDefault": true
    },

with this:

    "group": "build",

Modifying tasks.json

Starting November 3, 2024, MSYS2 has disabled wildcard support for mingw-w64 by default. This change impacts how wildcards like "*.cpp" are processed in build commands. To build multiple C++ files in your tasks.json, you must explicitly list the files, use a build system like make or cmake or implement the following workarounds: https://www.msys2.org/docs/c/#expanding-wildcard-arguments.

If you previously used "${workspaceFolder}/*.cpp" to compile all .cpp files in the current folder, this will no longer work directly. Instead, you can manually list the files or define a build script.

Debug helloworld.cpp

To debug your code,

  1. Go back to helloworld.cpp so that it is the active file.
  2. Set a breakpoint by clicking on the editor margin or using F9 on the current line.
    screenshot of breakpoint in helloworld.cpp

  3. From the drop-down next to the play button, select Debug C/C++ File.
    Screenshot of play button drop-down

  4. Choose C/C++: g++ build and debug active file from the list of detected compilers on your system (you’ll only be asked to choose a compiler the first time you run or debug helloworld.cpp).
    C++ debug configuration dropdown

The play button has two modes: Run C/C++ File and Debug C/C++ File. It will default to the last-used mode. If you see the debug icon in the play button, you can just select the play button to debug, instead of using the drop-down.

Explore the debugger

Before you start stepping through the code, let’s take a moment to notice several changes in the user interface:

  • The Integrated Terminal appears at the bottom of the source code editor. In the Debug Console tab, you see output that indicates the debugger is up and running.

  • The editor highlights the line where you set a breakpoint before starting the debugger:

    Initial breakpoint

  • The Run and Debug view on the left shows debugging information. You’ll see an example later in the tutorial.

  • At the top of the code editor, a debugging control panel appears. You can move this around the screen by grabbing the dots on the left side.

Step through the code

Now you’re ready to start stepping through the code.

  1. Select the Step over icon in the debugging control panel.

    This will advance program execution to the first line of the for loop, and skip over all the internal function calls within the vector and string classes that are invoked when the msg variable is created and initialized. Notice the change in the Variables window on the left.

    In this case, the errors are expected because, although the variable names for the loop are now visible to the debugger, the statement has not executed yet, so there is nothing to read at this point. The contents of msg are visible, however, because that statement has completed.

  2. Press Step over again to advance to the next statement in this program (skipping over all the internal code that is executed to initialize the loop). Now, the Variables window shows information about the loop variables.

  3. Press Step over again to execute the cout statement. (Note that the C++ extension does not print any output to the Debug Console until the loop exits.)

  4. If you like, you can keep pressing Step over until all the words in the vector have been printed to the console. But if you are curious, try pressing the Step Into button to step through source code in the C++ standard library!

    To return to your own code, one way is to keep pressing Step over. Another way is to set a breakpoint in your code by switching to the helloworld.cpp tab in the code editor, putting the insertion point somewhere on the cout statement inside the loop, and pressing F9. A red dot appears in the gutter on the left to indicate that a breakpoint has been set on this line.

    Then press F5 to start execution from the current line in the standard library header. Execution will break on cout. If you like, you can press F9 again to toggle off the breakpoint.

    When the loop has completed, you can see the output in the Integrated Terminal, along with some other diagnostic information that is output by GDB.

    Debug output in terminal

Set a watch

Sometimes you might want to keep track of the value of a variable as your program executes. You can do this by setting a watch on the variable.

  1. Place the insertion point inside the loop. In the Watch window, select the plus sign and in the text box, type word, which is the name of the loop variable. Now view the Watch window as you step through the loop.

  2. Add another watch by adding this statement before the loop: int i = 0;. Then, inside the loop, add this statement: ++i;. Now add a watch for i as you did in the previous step.

  3. To quickly view the value of any variable while execution is paused on a breakpoint, you can hover over it with the mouse pointer.

Customize debugging with launch.json

When you debug with the play button or F5, the C++ extension creates a dynamic debug configuration on the fly.

There are cases where you’d want to customize your debug configuration, such as specifying arguments to pass to the program at runtime. You can define custom debug configurations in a launch.json file.

To create launch.json, choose Add Debug Configuration from the play button drop-down menu.

You’ll then see a dropdown for various predefined debugging configurations. Choose C/C++: g++.exe build and debug active file.

C++ debug configuration dropdown

VS Code creates a launch.json file in the .vscode folder`, which looks something like this:

{
  "configurations": [
    {
      "name": "C/C++: g++.exe build and debug active file",
      "type": "cppdbg",
      "request": "launch",
      "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
      "args": [],
      "stopAtEntry": false,
      "cwd": "${fileDirname}",
      "environment": [],
      "externalConsole": false,
      "MIMode": "gdb",
      "miDebuggerPath": "C:\\msys64\\ucrt64\\bin\\gdb.exe",
      "setupCommands": [
        {
          "description": "Enable pretty-printing for gdb",
          "text": "-enable-pretty-printing",
          "ignoreFailures": true
        },
        {
          "description": "Set Disassembly Flavor to Intel",
          "text": "-gdb-set disassembly-flavor intel",
          "ignoreFailures": true
        }
      ],
      "preLaunchTask": "C/C++: g++.exe build active file"
    }
  ],
  "version": "2.0.0"
}

In the JSON above, program specifies the program you want to debug. Here it is set to the active file folder (${fileDirname}) and active filename with the .exe extension (${fileBasenameNoExtension}.exe), which if helloworld.cpp is the active file will be helloworld.exe. The args property is an array of arguments to pass to the program at runtime.

By default, the C++ extension won’t add any breakpoints to your source code and the stopAtEntry value is set to false.

Change the stopAtEntry value to true to cause the debugger to stop on the main method when you start debugging.

From now on, the play button and F5 will read from your launch.json file when launching your program for debugging.

Adding additional C/C++ settings

If you want more control over the C/C++ extension, you can create a c_cpp_properties.json file, which will allow you to change settings such as the path to the compiler, include paths, C++ standard (default is C++17), and more.

You can view the C/C++ configuration UI by running the command C/C++: Edit Configurations (UI) from the Command Palette (⇧⌘P (Windows, Linux Ctrl+Shift+P)).

Command Palette

This opens the C/C++ Configurations page. When you make changes here, VS Code writes them to a file called c_cpp_properties.json in the .vscode folder.

Here, we’ve changed the Configuration name to GCC, set the Compiler path dropdown to the g++ compiler, and the IntelliSense mode to match the compiler (gcc-x64).

Command Palette

Visual Studio Code places these settings in .vscode\c_cpp_properties.json. If you open that file directly, it should look something like this:

{
  "configurations": [
    {
      "name": "GCC",
      "includePath": ["${workspaceFolder}/**"],
      "defines": ["_DEBUG", "UNICODE", "_UNICODE"],
      "windowsSdkVersion": "10.0.22000.0",
      "compilerPath": "C:/msys64/mingw64/bin/g++.exe",
      "cStandard": "c17",
      "cppStandard": "c++17",
      "intelliSenseMode": "windows-gcc-x64"
    }
  ],
  "version": 4
}

You only need to add to the Include path array setting if your program includes header files that are not in your workspace or in the standard library path. It is strongly recommended not to add the system include path to the includePath setting for compilers that we support.

Compiler path

The extension uses the compilerPath setting to infer the path to the C++ standard library header files. When the extension knows where to find those files, it can provide features like smart completions and Go to Definition navigation.

The C/C++ extension attempts to populate compilerPath with a default compiler based on what it finds on your system. The extension looks in several common compiler locations but will only automatically select one that is in either one of the «Program Files» folders or whose path is listed in the PATH environment variable. If the Microsoft Visual C++ compiler can be found it will be selected, otherwise it will select a version of gcc, g++, or clang.

If you have more than one compiler installed, you might need to change compilerPath to match the preferred compiler for your project. You may also use the C/C++: Select InteliSense Configuration… command in the Command Palette to select one of the compilers that the extension detected.

Troubleshooting

MSYS2 is installed, but g++ and gdb are still not found

You must follow the steps on the MSYS2 website to use the MSYS CLI to install the full MinGW-w64 toolchain(pacman -S --needed base-devel mingw-w64-ucrt-x86_64-toolchain), as well as all required prerequisites. The toolchain includes g++ and gdb.

As a Windows user, running the pacman command gives me an error

UCRT on Windows machines is only included in Windows 10 or later. If you are using another version of Windows, run the following command that does not use UCRT:

pacman -S --needed base-devel mingw-w64-x86_64-toolchain

When adding the the MinGW-w64 destination folder to your list of environment variables, the default path will then be: C:\msys64\mingw64\bin.

MinGW 32-bit

If you need a 32-bit version of the MinGW toolset, consult the Downloading section on the MSYS2 wiki. It includes links to both 32-bit and 64-bit installation options.

Next steps

  • Explore the VS Code User Guide.
  • Review the Overview of the C++ extension.
  • Create a new workspace, copy your .vscode JSON files to it, adjust the necessary settings for the new workspace path, program name, etc. and start coding!

12/14/2023

MinGW (Minimalist GNU for Windows) is a free and open-source software development environment that allows users to create native Windows applications. It includes a collection of programming tools, compilers, and libraries, including GCC (GNU Compiler Collection) for C and C++. One of the critical steps when working with MinGW is ensuring that the MinGW installation directory is added to your system’s PATH. This allows you to compile and run your code directly from the Command Prompt or terminal without needing to navigate to the MinGW directory each time.

This detailed guide will walk you through the process of adding MinGW to the PATH variable in Windows 11. By the end, you’ll have everything you need to start coding in C or C++ using MinGW.

Step 1: Download and Install MinGW

Before you can add MinGW to your system PATH, you need to download and install it. Follow these steps:

  1. Download MinGW:

    • Open your web browser and navigate to the MinGW-w64 website.
    • You may also visit the SourceForge page for MinGW-w64.
    • Choose the appropriate version for your system (32-bit or 64-bit) and download the installer.
  2. Install MinGW:

    • Locate the downloaded installer and double-click it to run.
    • Follow the prompts in the setup wizard. When asked to select the installation directory, you can stick with the default or choose your desired directory (e.g., C:MinGW).
    • Make sure to include the GCC component in your installation options.
  3. Complete the Installation:

    • Continue through the installation process until MinGW is installed. You can close the installer once it completes.

Step 2: Locate Your MinGW Installation Directory

Once MinGW is installed, you need to determine the exact directory location for the bin folder that contains MinGW executables. Typically, this folder is located at:

  • For the default installation path: C:MinGWbin

If you customized your installation path during the setup, locate that directory instead.

Step 3: Add MinGW to System PATH

Now that you know where your MinGW installation is, it’s time to add it to your system PATH. Follow these steps to do this:

  1. Open Settings:

    • Click the Start menu or press the Windows key on your keyboard.
    • Type in “Settings” and hit Enter.
  2. Navigate to System Settings:

    • In the Settings window, click on the System tab on the left sidebar.
    • Scroll down and select About.
  3. Access Advanced System Settings:

    • On the right side of the About page, click on Advanced system settings.
  4. Open Environment Variables:

    • In the System Properties window, click on the Environment Variables button located at the bottom right corner.
  5. Locate the Path Variable:

    • In the Environment Variables window, you will see two sections — User variables and System variables.
    • To make MinGW available to your user only, select the Path variable under the User variables section, then click on Edit. If you want to add it for all users, do the same under the System variables section.
  6. Add MinGW Path:

    • In the Edit Environment Variable window, click on New.
    • Type or paste the path to the MinGW bin folder (e.g., C:MinGWbin) into the new entry.
    • Click OK to close the Edit Environment Variable window.
    • Click OK again to close the Environment Variables window, and finally, click OK in the System Properties window.

Step 4: Verify Your Installation

To ensure that MinGW has been successfully added to your PATH, follow these steps to verify:

  1. Open Command Prompt:

    • Press the Windows key + R to open the Run dialog.
    • Type cmd and hit Enter to open the Command Prompt.
  2. Check GCC Version:

    • In the Command Prompt window, type the following command:
      gcc --version
    • If MinGW has been successfully added to your PATH, you should see output displaying the version of GCC that is installed.

If you see an error message indicating that the command is not recognized, double-check the steps above to ensure you’ve entered the correct path.

Step 5: Compile and Run Your First Program

Now that you have MinGW set up and verified, let’s write a simple C program and compile it using MinGW.

  1. Create a Simple C Program:

    • Open a text editor (like Notepad) and enter the following sample C program:

      #include 
      
      int main() {
       printf("Hello, World!n");
       return 0;
      }
    • Save the file with a .c extension, for example, hello.c, in a directory of your choice (e.g., C:UsersYourUsernameDocuments).
  2. Compile the C Program:

    • Go back to the Command Prompt.
    • Navigate to the directory where you saved your C file. Use the cd (change directory) command for this. For example:
      cd C:UsersYourUsernameDocuments
    • Now compile the program using the gcc command:
      gcc hello.c -o hello
    • This command tells GCC to compile hello.c and output an executable named hello.exe.
  3. Run the Program:

    • After compiling the program, run the executable by typing:
      ./hello
    • You should see the output:
      Hello, World!

Congratulations! You have successfully added MinGW to your system’s PATH, compiled a C program, and executed it.

Troubleshooting Common Issues

Here are some common problems you may encounter, along with their solutions:

1. GCC not recognized

If you receive an error that the gcc command is not recognized, double-check the following:

  • Ensure MinGW is correctly installed.
  • Verify that the path you added to the system’s PATH variable points directly to the bin folder of your MinGW installation and is correctly configured.

2. Permissions Issues

If you encounter permission-related errors, it may be necessary to run Command Prompt in Administrator mode. Right-click on the Command Prompt shortcut and select Run as administrator.

3. Correcting Errors

If you experience issues while compiling code, take care to read the error messages that GCC returns. Typical errors include syntax errors, missing semicolons, and mismatched braces. The terminal will usually point you to the line of code where the error occurred, making it easier to troubleshoot.

Additional Resources

Learning C or C++

To further enhance your skills in C or C++, consider exploring online resources, books, or courses. Here are some suggestions:

  • Online Platforms:

    • Codecademy
    • Coursera
    • edX
  • Books:

    • «The C Programming Language» by Brian W. Kernighan and Dennis M. Ritchie
    • «C++ Primer» by Stanley B. Lippman, Josée Lajoie, and Barbara E. Moo

Community Support

Participating in programming communities can also boost your learning. Websites such as Stack Overflow and forums dedicated to C/C++ programming can provide assistance and insights from experienced developers.

Conclusion

In this guide, we explored how to download and install MinGW, add it to the PATH variable in Windows 11, verify the installation, and compile and run a simple C program. Keeping your development setup straightforward and efficient is crucial, and adding MinGW to your PATH is a vital step in ensuring ease of access to your development tools.

By following this guide, you can quickly start developing applications using MinGW on Windows 11. Whether you’re a beginner or an experienced programmer, having the right setup is key to successful software development. Happy coding!

MinGW-w64 — набор средств разработки для Windows, включает в себя компилятор GNU C/C++, отладчик gdb, профайлер gprof, системы сборки make и cmake и прочие утилиты комплекта GNU. MinGW расшифровывается, как Minimalistic Gnu for Windows. Проект отделился от проекта MinGW.

Сайт проекта: https://www.mingw-w64.org/

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

Существуют различные независимые сборки mingw-w64, большинство их которых распространяется в виде нескольких архивов, которые необходимо отдельно распаковывать. Разобраться в том, какие именно архивы нужно скачивать и распаковывать довольно сложно. Вариант установки с использованием exe-приложения, самостоятельно скачивающего нужные пакеты, к сожалению, содержит весьма устаревшую версию 8.1.0 компилятора.

Довольно простой способ установки (понадобится скачать только один архив) актуальной версии компилятора — это использование сайта winlibs.com.

Откройте этот сайт и перейдите к разделу «Download». Там будет довольно много разных ссылок на скачивание, расскажем как выбрать правильный архив, если вы не знаете в точности, что именно вам нужно.

Перейдите к разделу «Release versions» — «UCRT runtime». Выберите самую верхнюю версию MinGW в списке, она помечена, как LATEST. Вам нужна сборка с POSIX threads, версия для Win64. Если предлагаются варианты сборки с LLVM/Clang/LLD/LLDB, выберите вариант без (without) LLVM/Clang/LLD/LLDB (по крайней мере, если вы не знаете точно, что вам нужны именно LLVM/Clang/LLD/LLDB). Выберите zip-архив (если у вас установлен архиватор 7-zip, то можете скачать архив 7-zip, он меньше). То есть вам понадобится вот этот файл.

Выбор архива для скачивания mingw-w64 c winlibs.com

Прямая ссылка на скачивание архива с компилятором gcc 12.2.0 (последняя версия на февраль 2023): https://github.com/brechtsanders/winlibs_mingw/releases/download/14.2.0posix-19.1.1-12.0.0-ucrt-r2/winlibs-x86_64-posix-seh-gcc-14.2.0-mingw-w64ucrt-12.0.0-r2.zip

Внутри скачанного архива будет каталог mingw64. Распакуйте этот каталог на диск, лучше всего не использовать каталоги с пробелами или русскими буквами в именах (в том числе «Program Files»), поэтому лучше всего распаковать архив прямо в корень диска C:\. Далее будем считать, что у вас получился каталог C:\mingw64, внутри которого есть подкаталоги bin, include, lib, libexec, share и x86_64-w64-mingw32.

Добавление mingw-w64 в PATH

Для того, чтобы можно было использовать приложения из распакованного архива, а сторонние среды разработки, такие как Code::Blocks или Visual Studio Code могли найти компилятор, необходимо подкаталог bin из распакованного архива добавить в системную переменную Path.

Вам необходимо открыть окно «Свойства системы» панели управления Windows. Для этого нужно открыть проводник, сделать правый клик мышью на «Этот компьютер», выбрать «Свойства». Появится окно «Система — О системе», в котором нужно кликнуть на «Дополнительные параметры системы».

Или можно сразу открыть окно «Свойства системы», если нажать на Win+R, в строку «Открыть» ввести команду sysdm.cpl, затем нажать Enter.

В окне «Свойства системы» выберите вкладку «Дополнительно» и нажмите на «Переменные среды…». Верхний список — это переменные среды для текущего пользователя, нижний список — системные переменные. В списке системных переменных выберите Path и нажмите на кнопку «Изменить»… Нажмите на кнопку «Создать», в списке появится новая строка. Нажмите на кнопку «Обзор» и выберите каталог C:\mingw64\bin (или подкаталог bin подкаталога mingw64, если вы распаковали его в другое место). Нажмите на OK, затем на OK, затем на OK.

Подробней про переменные среды и их изменение можно прочитать здесь.

Проверка работы компилятора

После распаковки архива и добавления MinGW-w64 в Path, запустите командную строку. Нажмите на Win+R и введите команду cmd, затем нажмите Enter.

Наберите команду g++. Вы должны увидеть сообщение «g++: fatal error: no input files compilation terminated». Наберите команду

g++ --version

Вы увидите сообщение с версией компилятора. Убедитесь, что версия соответствует той, которую вы скачали.

Пример вывода g++ из командной строки для проверки работы и версии компилятора

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.

Пост ориентирован на новичков. В нем не рассматривается настройка Visual Studio. Он научит вас настраивать некоторые текстовые редакторы на компиляцию OpenGL приложений, либо выполнять это из консоли вручную.

Недавно, наконец, вышло 8-е издание книги OpenGL programming guide, которую я ждал уже более чем 2 года. Чуть раньше я познакомился с замечательным текстовым редактором Sublime Text 2 и решил настроить его вместо установки тяжелой Visual Studio.

Итак, для начала нам нужен компилятор — я остановился на G++. Он является частью GCC, а его порт под Windows называется MinGW. С него и начнем:

MinGW

Качаем с официального сайта инсталлятор и запускаем его. Можно выбрать выкачивание свежих пакетов сразу при установке, либо обновить их вручную позже. Компиляторы Fortran, Ada и ObjC нам не понадобятся, их можно не ставить. MSYS Basic System может пригодится, его ставим. В качестве адреса я указал «C:\MinGW«, но если вас это смущает — можете выбрать другой, например, «C:\Program Files\Common Files\MinGW«.

После установки следует добавить к системной переменной PATH две новые папки: «MinGW\bin» и «MinGW\msys\1.0\bin«. Для этого заходим в Пуск -> Панель управления -> Система -> Дополнительные параметры системы; Во вкладке Дополнительно тыкаем внизу кнопку Переменные среды. Из списка системных переменных выбираем Path, и через точку с запятой дописываем полные адреса к папкам «MinGW\bin» и «MinGW\msys\1.0\bin«.

Если вы не выбирали выкачивание свежих пакетов при установке, следует обновить нужные пакеты вручную. Для этого открываем консоль (Win+R -> cmd), и пишем следующие команды:

mingw-get update

Обновит информацию о доступных пакетах,

mingw-get show gсс
mingw-get show g++

Отобразит полные имена пакетов gcc и g++,

mingw-get upgrade mingw32-gcc
mingw-get upgrade mingw32-gcc-g++

Обновит эти пакеты до последних доступных для MinGW версий.

Теперь, когда у нас есть компилятор, мы можем приступить к установке необходимых OpenGL библиотек.

Freeglut

Поскольку OpenGL это API, которое относится исключительно к графике — в него не входят функции по созданию окон или обработки устройств ввода. Тем более, решение этой задачи зависит от операционной системы. По-этому ее вынесли в отдельную библиотеку и назвали GLUT — OpenGL Utility Toolkit. Однако, последний релиз этой библиотеки был очень давно и сейчас ее подменила freeglut.

Качаем с официального сайта бинарники под MinGW. Распаковываем, freeglut.dll из папки bin кидаем в «C:\Windows\System32» (для х86) или «C:\Windows\SysWOW64» (для х64), или любую другую папку, которая указана в PATH. Содержимое папок include и lib можно скопировать либо в «MinGW\include» и «MinGW\lib» (так будет проще), либо в отдельные созданые папки «MinGW\freeglut\include» и «MinGW\freeglut\lib«.

На этом с freeglut все. Для его подключения нужно добавить #include <GL/freeglut.h>

glew

Библиотека glew позволяет определять что видеокарта поддерживает, а что — нет. Ее установка немного сложнее для нашего случая.
Качаем с официального сайта исходники, поскольку бинарники заточены под Visual Studio и нам не подойдут. Теперь эти исходники нужно скомпилировать. Я в этом практически ничего не понимаю, по-этому обратился к гуглу и нашел помощь здесь:
Распаковываем скачанный архив, открываем консоль, заходим в полученную папку и пишем следующие команды:

gcc -DGLEW_NO_GLU -O2 -Wall -W -Iinclude -DGLEW_BUILD -o src/glew.o -c src/glew.c
gcc -shared -Wl,-soname,libglew32.dll -Wl,--out-implib,lib/libglew32.dll.a -o lib/glew32.dll src/glew.o -L/mingw/lib -lglu32 -lopengl32 -lgdi32 -luser32 -lkernel32
ar cr lib/libglew32.a src/glew.o

В результате в папке lib появилось 3 файла: glew32.dll, glew32.dll.a и glew32.a.
glew32.dll копируем туда же, куда ранее скопировали freeglut.dll, остальные 2 — в папку «MinGW\lib» либо «MinGW\glew\lib«.
Из папки include копируем содерижмое в «MinGW\include» или «MinGW\glew\include«.

На этом с glew все. Для его подключения нужно добавить #include <GL/glew.h>, но сделать это необходимо перед подключением других gl библиотек.

Проверяем работоспособность

Создаем минимальный test.cpp:

#include <iostream>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <GL/gl.h>

int main(int argc, char** argv) {

	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_RGBA);
	glutInitWindowSize(512, 512);
	glutInitContextVersion(4, 1); // Версия OpenGL, которую вы хотите использовать
	glutInitContextProfile(GLUT_CORE_PROFILE);
	glutCreateWindow(argv[0]);

	if (glewInit()) {
		std::cerr << "Unable to initialize GLEW ... exiting\n";
		exit(EXIT_FAILURE);
	}

	glutMainLoop();

}

Обратите внимание на функцию glutInitContextVersion — она завершит выполнение программы если ей не удалось создать контекст для указаной версии OpenGL. Чтобы узнать версию OpenGL, которую поддерживает ваша видеокарта, можно заглянуть в ее спецификацию либо скачать бинарники glew с официального сайта и запустить glewinfo.exe из папки bin. Он сгенерирует файл glewinfo.txt, в котором будет детально расписано что ваша видеокарта поддерживает, а что — нет. Иногда функционал можно расширить установкой более свежего видеодрайвера.

Открываем консоль, заходим в папку с test.cpp и пишем следующую команду:

g++ -o test.exe test.cpp -lglew32 -lfreeglut -lopengl32 -lglu32 -Wl,--subsystem,windows

В случае, если вы создавали отдельные папки freeglut и glew, здесь необходимо дополнительно указать соответствующие дополнительные папки include и lib. Тогда пример команды выглядит так:

g++ -o test.exe test.cpp -lglew32 -lfreeglut -lopengl32 -lglu32 -Wl,--subsystem,windows -I"C:\MinGW\freeglut\include" -L"C:\MinGW\freeglut\lib" -I"C:\MinGW\glew\include" -L"C:\MinGW\glew\lib"

Флаг -Wl,--subsystem,windows указывает компилятору что он должен создать графическое приложение, а не консольное.
Если все получилось, должен получится файл test.exe, который при запуске создает белое окно 512х512.

Когда вы захотите поделится своим приложением, убедитесь что вместе с исполняемым файлом передаете используемые библиотеки — freeglut.dll и glew32.dll.

Sublime Text 2

Ну и напоследок, приведу пример настройки Sublime. Скачать его можно отсюда, вводные видео-уроки на английском языке можно глянуть здесь.
После установки открываем файл настройки билда С++:
«C:\Users\%Username%\AppData\Roaming\Sublime Text 2\Packages\C++\C++.sublime-build«
Сохраняем его копию как
«C:\Users\%Username%\AppData\Roaming\Sublime Text 2\Packages\User\C++\С++ OpenGL.sublime-build«

Строчку

"cmd": ["g++", "${file}", "-o", "${file_path}/${file_base_name}"],

дополняем подключением библиотек:

"cmd": ["g++", "${file}", "-o", "${file_path}/${file_base_name}", "-lfreeglut -lopengl32 -lglew32 -Wl,--subsystem,windows"],

Аналогично, строчку

"cmd": ["bash", "-c", "g++ '${file}' -o '${file_path}/${file_base_name}' && '${file_path}/${file_base_name}'"]

дополняем до

"cmd": ["bash", "-c", "g++ '${file}' -o '${file_path}/${file_base_name}' -lglew32 -lfreeglut -lopengl32 -lglu32 -Wl,--subsystem,windows && '${file_path}/${file_base_name}'"]

Если вы создавали отдельные папки под freeglut и glew, эти команды следует дополнить указанием адресов дополнительных папок include и lib.

Для того чтобы Sublime не отказывался выводить кириллицу в свою консоль, после

"selector": "source.c, source.c++",

добавляем

"encoding": "cp1251",

Теперь, когда у нас открыт test.cpp, выбираем Tools -> Build system -> C++ OpenGL.
Нажимаем Ctrl+B для компиляции, Ctrl+Shift+B для компиляции и запуска.

На этом все!

UPD: Когда дело дошло до кода с gl-функциями из последних версий, выяснилось, что подключение заголовочного файла GL/gl.h недостаточно. В нем содержится устаревшая версия 1.1, и этот файл больше не обновляется. В дополнение к нему необходимо подключить GL/glext.h (последнюю версию которого надо скачать отсюда) и GL/wglext.h (отсюда). Для линукса последний файл заменяется GL/glxext.h (ссылка). Скачанными файлами нужно заменить их устаревшие версии по адресу «MinGW/include/GL/«.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Microsoft windows terminalservices remoteconnectionmanager
  • Как зайти в биос на пк windows 10 pro
  • Нет paint в windows 11
  • Не отображается блютуз на ноутбуке windows 11
  • Npm windows что это