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

Configuring the C++ extension in Visual Studio Code to target g++ and gdb on a Mingw-w64 installation

Using GCC with MinGW

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 and debug a simple Hello World program in VS Code. 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

  3. 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. You can download the latest installer from the MSYS2 page or use this link to the installer.

  4. Follow the Installation instructions on the MSYS2 website to install Mingw-w64. Take care to run each required Start menu and pacman command.

  5. Install the Mingw-w64 toolchain (pacman -S --needed base-devel mingw-w64-x86_64-toolchain). Run the pacman command in a MSYS2 terminal. Accept the default to install all the members in the toolchain group.

  6. Add the path to 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. Choose the Path variable in your User variables and then select Edit.
    4. Select New and add the Mingw-w64 destination folder path to the system path. The exact path depends on which version of Mingw-w64 you have installed and where you installed it. If you used the settings above to install Mingw-w64, then add this to the path: C:msys64mingw64bin.
    5. Select OK to save the updated PATH. You will need to reopen any console windows for the new PATH location 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
  1. If you don’t see the expected output or g++ or gdb is not a recognized command, make sure your PATH entry matches the Mingw-w64 binary location where the compilers are located. If the compilers do not exist at that PATH entry, make sure you followed the instructions on the MSYS2 website to install Mingw-w64.
  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.
    • Missing the mingw-w64-gdb package is one cause of the «The value of miDebuggerPath is invalid.» message upon attempted compilation if your PATH is correct.

Create Hello World

From a Windows command prompt, create an empty folder called projects where you can place all your VS Code projects. Then create a sub-folder called helloworld, navigate into it, and open VS Code in that folder by entering the following commands:

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 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 checking Auto Save in the main File menu.

The Activity Bar on the far left lets you open different views such as Search, Source Control, and Run. You’ll look at the Run view later in this tutorial. 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

In your new helloworld.cpp file, hover over vector or string to see type information. After the declaration of the msg variable, start typing msg. as you would when calling a member function. You should immediately see a completion list that shows all the member functions, and a window that shows the type information for the msg object:

Statement completion IntelliSense

You can press the Tab key to insert the selected member; then, when you add the opening parenthesis, you will see information about any arguments that the function requires.

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 a C++ compiler installed 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

The first time you run your program, the C++ extension creates tasks.json, which you’ll find in your project’s .vscode folder. tasks.json stores 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\mingw64\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 that will be passed to g++. These arguments must be specified in the order expected by the compiler.

This task tells g++ to take the active file (${file}), compile it, and create an executable file in the current directory (${fileDirname}) with the same name as the active file but with the .exe extension (${fileBasenameNoExtension}.exe), resulting in helloworld.exe for our example.

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 as the description of the task in the tasks list. It’s highly recommended to rename this value to differentiate it from similar tasks.

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. 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

You can modify your tasks.json to build multiple C++ files by using an argument like "${workspaceFolder}/*.cpp" instead of ${file}.This will build all .cpp files in your current folder. You can also modify the output filename by replacing "${fileDirname}\${fileBasenameNoExtension}.exe" with a hard-coded filename (for example "${workspaceFolder}\myProgram.exe").

Debug helloworld.cpp

  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
    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/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 click the play button to debug, instead of using the drop-down.

screenshot of play button in debug mode

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 Output 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.

    Debugging controls

Step through the code

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

  1. Click or press the Step over icon in the debugging control panel.

    Step over button

    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.

    Debugging windows

    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 as of the March 2019 release, 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!

    Breakpoint in gcc standard library header

    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.

    Breakpoint in main

    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, click 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.

    Watch window

  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.

    Mouse hover

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.

Add debug configuration play button 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, which looks something like this:

{
  "version": "0.2.0",
  "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\mingw64\bin\gdb.exe",
      "setupCommands": [
        {
          "description": "Enable pretty-printing for gdb",
          "text": "-enable-pretty-printing",
          "ignoreFailures": true
        }
      ],
      "preLaunchTask": "C/C++: g++.exe build active file"
    }
  ]
}

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.

C/C++ configurations

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 .vscodec_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.18362.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.

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 the default compiler location based on what it finds on your system. The extension looks in several common compiler locations.

The compilerPath search order is:

  • First check for the Microsoft Visual C++ compiler
  • Then look for g++ on Windows Subsystem for Linux (WSL)
  • Then g++ for Mingw-w64.

If you have Visual Studio or WSL installed, you may need to change compilerPath to match the preferred compiler for your project. For example, if you installed Mingw-w64 version 8.1.0 using the i686 architecture, Win32 threading, and sjlj exception handling install options, the path would look like this: C:Program Files (x86)mingw-w64i686-8.1.0-win32-sjlj-rt_v6-rev0mingw64bing++.exe.

Troubleshooting

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

You must follow the steps on the MSYS2 website and use the MSYS CLI to install Mingw-w64, which contains those tools. You will also need to install the full Mingw-w64 toolchain (pacman -S --needed base-devel mingw-w64-x86_64-toolchain) to get the gdb debugger.

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, and so on, and start coding!

5/13/2022

In this article we will learn that how to install gcc windows 10. Download and install gcc windows. GCC is compiler for C/C++ language.

This post about how to install gcc ?

Visual Studio Express and the system GCC compiler included in several modern Linux distributions still lack many modern C++ features.

One such function is generic lambdas, also known as polymorphic lambdas.

However, this function is included in the most recent versions of GCC and Clang.

The instructions below will take you through downloading the most current version of GCC on Windows, allowing you to play with generic lambdas and other cutting-edge C++ features.

You’ll have to compile GCC from source, but that shouldn’t be a concern.

These topics we will cover in this article :–[]
  • What is compiler ?
  • What is MinGW and GCC ?
  • Download and install MinGW Compiler on windows .
  • Verify the installation.

Introduction :–[]

What is compiler ?

A compiler is a computer program  that transforms code written in one programming language into code written in another.

The term “compiler” refers to programs that convert source code from a high-level programming language to a lower-level programming language in order to produce an executable program.

  • Compiler is a program that processes a statement written in particular programming language.
  • A computer is not take source code directly. So ,a compiler takes our written code and covert into Machine code that a computer’s system process.
  • Example : MinGW GCC Compiler for C/C++ , Java JDK for Java.
  • There are three types of compilers :- 1.Single Pass Compiler , 2. Two Pass Complier and 3. Multi pass Compiler

What is MinGW and GCC ?[]

MinGW (formerly mingw32) is a free and open source software development environment for creating Microsoft Windows applications. With the launch of the Mingw-w64 project in 2005–2008, the progress of the MinGW project was split in two.

MinGW provides a Windows native build of the GNU Compiler Collection (GCC), GNU Binutils for Windows (assembler, linker, archive manager), a series of freely distributable Windows related header files and static import libraries that allow the use of the Windows API, and miscellaneous utilities.

MinGW does not depend on a third-party dynamic-link library (DL) for C runtime.

Since the runtime libraries are not distributed under the GNU General Public License (GPL).

It is not mandatory to share the source code for the program generated, unless a GPL library is included elsewhere in the software.

MinGW can run natively on Microsoft Windows, cross-hosted on Linux (or other Unix), or “cross-natively” on Cygwin.

Despite the fact that MinGW program are 32-bit executables, they can be found in both 32-bit and 64-bit models of Windows.

  • MinGW stands for Minimal GNU for Windows.
  • MinGW contains GCC which in the collection of GNU free Software.
  • It is a GCC-based compiler that compiles and connects windows code.
  • Uses the Microsoft runtime libraries.
  • distributed with the Windows operating system.
  • GCC stands for GNU Compiler Collections.
  • Used to compile C and C++ language.
  • GCC can compile any .C or .CPP files but they’ll be considered C and C++, respectively.
  • Any .C or .CPP files can be compiled with g++ , but they will only be handled as C++ files.

Download and install MinGW/gcc Compiler on windows ?[]

MinGW-w64 is a fork of MinGW that is designed to run on 64-bit Windows (as well as the 32-bit windows). http://mingw-w64.org/doku.php is the mother port.

GNU is a source of open source programming software, and MinGW stands for Minimalist GNU for Windows (GNU stands for GNU is Not Unix).

In this handout, you’ll get the files you’ll need for GNU C++, and in the next, you’ll get a version of Eclipse that’s already configured to work with MinGW.

Before you started, you might want to print these instructions so that you can refer to them when downloading and installing MinGW.

Alternatively, you should simply bookmark this page in your browser. Until executing the action mentioned in – step, make sure you read it absolutely.

Download MinGW :–[]

  • To Download MinGW Click here. Following Screen appear after open this link in new tab.
  • Click on ‘mingw-get-setup.exe(86.5 kb)’ . This is MinGW installer setup.
  • Following Screen appear . The file will starting automatically download in standard download folder. It will download quickly.
  • Go into your downloads folder and run the .exe file.
  • popup appear on screen. Click on yes.
  • Following window appear on screen.
  • Click on Install.
  • Install on default directory or change if you want to change. Click Continue.
  • Download is in process. MinGW is downloading required filles.
  • Click Continue download is completed.
  • Following window will appear after download is complete . check on mingw32-base , mingw32-gcc-g++ and msys-base.
  • After click on checkbox click on installation and click on Apply.
  • Following window will appear. Download is started. This is final installation.
  • Than close the window and go in the installation directory C:MinGW .
  • Go into bin folder. click on address bar and copy the path C:MinGWbin.
  • Go to System properties.
  • Than go to Advanced system settings.
  • Click on Environment variables to go into path setttings.
  • Press click on Path and than click on Edit to add GCC to path.
  • Click on New to create new path .
  • Paste the path copied you and click ok. Now everything is ok. MinGW is successfully installed and added to path. Now you verify that MinGW is working or not.

Verify the installation :–[]

Now everything is ok. Now verify that the MinGW was successfully install on your computer.

  • Open cmd and type command gcc. The following window will appear after this command.
  • You should get output : gcc: no input files. it means that the gcc successfully installed in your computer. If you get other output try again this process and verify again.
  • Download any code editor or IDE and lets start coding.

Thank you for visiting our website and reading this blog post. We hope that this post was very helpful for you. If you think this post was helpful for you , please share it.

Give us your feedback in comments. Continue visit our website to get daily more helpful posts. Thank you again.

For more helpful posts and updates please keep visiting our website.

Read more

more posts

In this article we will learn that how to install gcc windows 10. Download and install gcc windows. GCC is compiler for C/C++ language.

This post about how to install gcc ?

Visual Studio Express and the system GCC compiler included in several modern Linux distributions still lack many modern C++ features.

One such function is generic lambdas, also known as polymorphic lambdas.

However, this function is included in the most recent versions of GCC and Clang.

The instructions below will take you through downloading the most current version of GCC on Windows, allowing you to play with generic lambdas and other cutting-edge C++ features.

You’ll have to compile GCC from source, but that shouldn’t be a concern.

These topics we will cover in this article :–[]
  • What is compiler ?
  • What is MinGW and GCC ?
  • Download and install MinGW Compiler on windows .
  • Verify the installation.

Introduction :–[]

What is compiler ?

A compiler is a computer program  that transforms code written in one programming language into code written in another.

The term “compiler” refers to programs that convert source code from a high-level programming language to a lower-level programming language in order to produce an executable program.

  • Compiler is a program that processes a statement written in particular programming language.
  • A computer is not take source code directly. So ,a compiler takes our written code and covert into Machine code that a computer’s system process.
  • Example : MinGW GCC Compiler for C/C++ , Java JDK for Java.
  • There are three types of compilers :- 1.Single Pass Compiler , 2. Two Pass Complier and 3. Multi pass Compiler

What is MinGW and GCC ?[]

MinGW (formerly mingw32) is a free and open source software development environment for creating Microsoft Windows applications. With the launch of the Mingw-w64 project in 2005–2008, the progress of the MinGW project was split in two.

MinGW provides a Windows native build of the GNU Compiler Collection (GCC), GNU Binutils for Windows (assembler, linker, archive manager), a series of freely distributable Windows related header files and static import libraries that allow the use of the Windows API, and miscellaneous utilities.

MinGW does not depend on a third-party dynamic-link library (DL) for C runtime.

Since the runtime libraries are not distributed under the GNU General Public License (GPL).

It is not mandatory to share the source code for the program generated, unless a GPL library is included elsewhere in the software.

MinGW can run natively on Microsoft Windows, cross-hosted on Linux (or other Unix), or “cross-natively” on Cygwin.

Despite the fact that MinGW program are 32-bit executables, they can be found in both 32-bit and 64-bit models of Windows.

  • MinGW stands for Minimal GNU for Windows.
  • MinGW contains GCC which in the collection of GNU free Software.
  • It is a GCC-based compiler that compiles and connects windows code.
  • Uses the Microsoft runtime libraries.
  • distributed with the Windows operating system.
  • GCC stands for GNU Compiler Collections.
  • Used to compile C and C++ language.
  • GCC can compile any .C or .CPP files but they’ll be considered C and C++, respectively.
  • Any .C or .CPP files can be compiled with g++ , but they will only be handled as C++ files.

Download and install MinGW/gcc Compiler on windows ?[]

MinGW-w64 is a fork of MinGW that is designed to run on 64-bit Windows (as well as the 32-bit windows). http://mingw-w64.org/doku.php is the mother port.

GNU is a source of open source programming software, and MinGW stands for Minimalist GNU for Windows (GNU stands for GNU is Not Unix).

In this handout, you’ll get the files you’ll need for GNU C++, and in the next, you’ll get a version of Eclipse that’s already configured to work with MinGW.

Before you started, you might want to print these instructions so that you can refer to them when downloading and installing MinGW.

Alternatively, you should simply bookmark this page in your browser. Until executing the action mentioned in – step, make sure you read it absolutely.

Download MinGW :–[]

  • To Download MinGW Click here. Following Screen appear after open this link in new tab.
  • Click on ‘mingw-get-setup.exe(86.5 kb)’ . This is MinGW installer setup.
  • Following Screen appear . The file will starting automatically download in standard download folder. It will download quickly.
  • Go into your downloads folder and run the .exe file.
  • popup appear on screen. Click on yes.
  • Following window appear on screen.
  • Click on Install.
  • Install on default directory or change if you want to change. Click Continue.
  • Download is in process. MinGW is downloading required filles.
  • Click Continue download is completed.
  • Following window will appear after download is complete . check on mingw32-base , mingw32-gcc-g++ and msys-base.
  • After click on checkbox click on installation and click on Apply.
  • Following window will appear. Download is started. This is final installation.
  • Than close the window and go in the installation directory C:MinGW .
  • Go into bin folder. click on address bar and copy the path C:MinGWbin.
  • Go to System properties.
  • Than go to Advanced system settings.
  • Click on Environment variables to go into path setttings.
  • Press click on Path and than click on Edit to add GCC to path.
  • Click on New to create new path .
  • Paste the path copied you and click ok. Now everything is ok. MinGW is successfully installed and added to path. Now you verify that MinGW is working or not.

Verify the installation :–[]

Now everything is ok. Now verify that the MinGW was successfully install on your computer.

  • Open cmd and type command gcc. The following window will appear after this command.
  • You should get output : gcc: no input files. it means that the gcc successfully installed in your computer. If you get other output try again this process and verify again.
  • Download any code editor or IDE and lets start coding.

Thank you for visiting our website and reading this blog post. We hope that this post was very helpful for you. If you think this post was helpful for you , please share it.

Give us your feedback in comments. Continue visit our website to get daily more helpful posts. Thank you again.

For more helpful posts and updates please keep visiting our website.

Read more

more posts

Cover image for How to install gcc in Windows 10? (the easier way)

Sudev Suresh Sreedevi

GCC, abbreviation for ‘GNU Compiler Collection’ (thanks @saphirakai
) (and not Gulf Cooperation Council, like I’d assumed) is a necessity if you (or your pesky college) is into C Programming.

Almost all Linux distros come pre-installed with it so they are out of the trouble. But for those of you who were constant users of Windows and Command Prompt, and never felt the necessity for a C compiler, GCC seems to come out of the blue and a tough nut to install. 1000 rage-quits later, I present you this article.

This article is written so that the installation process is made easier than most of the trashy articles I had to go through.

Installation

  1. Go to MinGW official website and click on ‘Downloads’ on the left panel. You’ll be redirected to the site which hosts the files.
    Important Edit: MinGW official website is now down (as of 24th March 2021). Hence, instead of their official website, download from MinGW SourceForge page
  2. Look for mingw-get-setup.exe for downloading. Download it and launch the installer. Accept the terms and move on.
  3. You’ll now see that the installer is connecting to the Internet and downloading a lot of tiny and small files. Wait till it ends.
  4. Right when it ends (which won’t take long), you’ll be presented a window with title MinGW Installation Manager. You should be in the ‘Basic Setup’ tab by default when it launches. If not, click on Basic Setup.
  5. Out of the numerous check boxes presented to you on the right side, tick «mingw32-gcc-g++-bin«. If you are prompted with a menu, click on Mark for Install.
  6. Then on the top left corner click on Installation > Apply Changes. And wait while it downloads a billion files and installs them.

MinGW Installation Manager

  1. Now you gotta edit your «Environment Variables» as well, so that gcc works in cmd no matter the file location.
  2. For that go to Windows Explorer > Right click on This PC > Properties > Advanced system settings > Environment Variables or you could just search for «Environment Variables» in Windows Search…
  3. At the bottom «System Variables» panel, look for a Variable named «Path» and double click on it. Some systems show a good UI for adding a New Path easily (by clicking New), else you just need to add ; at the end and add the following path

    C:MinGWbin
    

    (This is assuming you didn’t manually change any installation paths and went with just clicking ‘Next’ during installation)

  4. Click on OK, and OK and close the other windows. Open a Command Prompt Terminal and try typing gcc --version and press Enter.

    If you get something like

    gcc (MinGW.org GCC Build-2) 9.2.0
    Copyright (C) 2019 Free Software Foundation, Inc.
    This is free software; see the source for copying conditions. 
    There is NO warranty; not even for MERCHANTABILITY or FITNESS
    FOR A PARTICULAR PURPOSE.
    

    gcc has been successfully installed in your PC. Enjoy!

Cheers and happy coding!

Join us at DEV Want to join the conversation?
 

It’s easy! Become a DEV member to follow this post, comment, and more.

Installation

To check if GCC already exists by running the following command in your command promt gcc -v

  • Install MSYS2 MSYS2.

  • This will install the linux shell on your Machine.

  • Update packages and mirrors using pacman -Syu.

  • You may have to restart

  • To install GCC copy the following code and paste in the shell Ctrl + v might not work

  • Note: Keep pressing ENTER to select the default installation instructions.

pacman -S --needed base-devel mingw-w64-i686-toolchain mingw-w64-x86_64-toolchain git subversion mercurial mingw-w64-i686-cmake mingw-w64-x86_64-cmake
  • This command will take a while to download and install all files.
  • After this GCC is installed but you still need to add it to your path.
  • Note: IF you get the following error gcc is not recognized as an internal or external command GCC may not be added to your path

PATH

  • To set the path to GCC Compiler

  • Open Start and type environment variables

  • Click Advanced System Settings

  • Click Environment Variables

  • In the System variables section add a new entry to PATH/ Path.

  • Add the following two lines

  • C:msys64mingw64bin and C:msys64ming32bin

  • Note: The path may vary according to where you have installed MSYS2

  • GCC installation is complete you may use gcc to compile programs
    If you still get this error
    gcc is not recognized as an internal or external command
    try this

Compiling

Locate your program
I will be giving this example considering .c program
cd into your desired directory where file is locate or type cmd in the adress bar
then type command
gcc -o name name.c
eg. gcc -o helloworld helloworld.c
The name after -o is the name given to exe file that is generated
Correct errors if any and run the above command again when done
If no errors are generated
Type name that is the name of your .exe
the program will have run

CODE::BLOCKS

You could also download CODE::BLOCKS IDE which comes with the GCC compiler
Download the binary release from here
Download the one that says mingw-setup.exe
Make sure that you dont have gcc previously installed in your computer
Follow the instructions
You will have to set the path manually as we did previously
The bin lies in C:Program Files(x86)|CodeBlocksMinGWbin

MinGW
MSYS2
GCC
CodeBlocks
More
Installing CodeBlocks

Thank you

I am using Visual Studio Code on Windows 10 and I am trying to build a program (called Bus from the source file Bus.cpp) with g++ from MinGW. I modified the tasks.json file using various methods that I have read from previous threads. I am providing screenshots of the tasks.json file and the results after building (ctrl + shift + b). I am also providing my questions below.

Method 1

Method 2

Method 3

Method 4

Question 1) I want to be able to build and create a program called «bus» using method 1. However, I have to replace «g++» with the directory path of the MinGW’s g++ compiler (as shown in method 2). What do I have to do in order to just put «g++» instead of the path to MinGW’s g++.exe?

Question 2) It looks like it compiled using methods 2 and 4 which provide the directory path to MinGW’s g++ compiler but I do not see the built program called «bus» even though I used «-o bus» in the command. Why do I not see it?

EDIT TO SHOW CODES:

First Method tasks.json file:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "g++ -g bus.cpp -o bus",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

First Method resulting output:

> Executing task: g++ -g bus.cpp -o bus <

g++ : The term 'g++' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name,
or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ g++ -g bus.cpp -o bus
+ ~~~
    + CategoryInfo          : ObjectNotFound: (g++:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The terminal process terminated with exit code: 1

Terminal will be reused by tasks, press any key to close it.

Second Method tasks.json file:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "C:/MinGW/bin/g++.exe -g bus.cpp -o bus",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Second Method resulting output:

> Executing task: C:/MinGW/bin/g++.exe -g bus.cpp -o bus <

The terminal process terminated with exit code: 1

Terminal will be reused by tasks, press any key to close it.

Third Method tasks.json file:
{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "g++",
            "args": [
                "-g", "bus.cpp", "-o", "bus"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Third Method resulting output:

    > Executing task: g++ -g bus.cpp -o bus <

g++ : The term 'g++' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name,
or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ g++ -g bus.cpp -o bus
+ ~~~
    + CategoryInfo          : ObjectNotFound: (g++:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

The terminal process terminated with exit code: 1

Terminal will be reused by tasks, press any key to close it.

Fourth Method tasks.json file:

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "C:/MinGW/bin/g++",
            "args": [
                "-g", "bus.cpp", "-o", "bus"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Fourth Method resulting output:

    > Executing task: C:/MinGW/bin/g++ -g bus.cpp <

The terminal process terminated with exit code: 1

Terminal will be reused by tasks, press any key to close it.

11 mins read

Follow these steps to install g++ (the GNU C++ compiler) for Windows. There is no room for creativity here; you must follow the directions exactly.

  1. Pick the drive and a folder in which you want to install g++. I’ll assume that it is C:, but you can choose a different one. If you choose a different drive or a different folder, you’ll need to adapt the directions below accordingly.
  2. Download full.exe, an about 14 megabyte executable, to C:full.exe by right-clicking on the link. Use Save Link As… or Save Target As… Be sure the browser saves the file as C:full.exe.
  3. Run the downloaded executable. This will install g++ (and a lot of other things that you don’t really need) on your hard drive. Go to the C: drive using Windows Explorer and double-click on full.exe. Or, open a DOS command prompt window (Start > Programs > Command Prompt), connect to the C: drive using the cd command, and type full.
  4. Locate where the bin folder was created for the g++ installation. On my Windows machine, it was created in the following path: C:cygnuscygwin-b20H-i586-cygwin32bin You now should add it to the PATH environment variable. You do that by following: Start -> Control Panel -> System -> Advanced -> Environment Variables At this point you can see the PATH variable either in the User Variables or in the System Variables. Add the g++ path into the PATH variable. You add it to the end of the existing value separated by a semicolon (‘;’). Make sure that you do not lose the original value. You are just appending more to the end separated by a semicolon.
  5. Restart your computer. A Cygnus Solutions entry will appear in your Programs menu, and an icon may appear on your desktop. Don’t use them! You will use it using the g++ command on a DOS command prompt as explained below.

You should now be able to run g++ from a DOS command prompt window. For example, to compile a file called C:minehello.cpp, connect to the C:mine folder and enter

g++ -g hello.cpp -o hello -lm

You’ll then be able to run the compiled program by entering hello in the DOS command prompt window.

If you’ve installed Emacs as described here, you will also be able to run g++ from Emacs. If, when you do this, Emacs tries to compile with the command make -k, you made a mistake during the Emacs installation. (If you try to compile a C program, e.g., hello.c instead of a C++ program, e.g., hello.cpp, it will try to make -k. In that case enter the compile command, gcc -g hello.c -o hello -lm, manually. After you try it manually once, from the second time on it will do the right thing automatically.) If you want to learn how to run g++ on emacs, see here.

If you’d like to learn more about where this free compiler came from, we downloaded it from an older site of http://sourceware.org/cygwin/.

If you wish to clean up a little, you may delete the file: full.exe at this point. Your g++ compiler is installed under C:cygnus.

Several modern C++ features are currently missing from Visual Studio Express, and from the system GCC compiler provided with many of today’s Linux distributions. Generic lambdas – also known as polymorphic lambdas – are one such feature. This feature is, however, available in the latest versions of GCC and Clang.

The following guide will help you install the latest GCC on Windows, so you can experiment with generic lambdas and other cutting-edge C++ features. You’ll need to compile GCC from sources, but that’s not a problem. Depending on the speed of your machine, you can have the latest GCC up and running in as little as 15 minutes.

The steps are:

  1. Install Cygwin, which gives us a Unix-like environment running on Windows.
  2. Install a set of Cygwin packages required for building GCC.
  3. From within Cygwin, download the GCC source code, and build and install it.
  4. Test the new GCC compiler in C++14 mode using the -std=c++14 option.

You can also install native GCC compilers from the MinGW-w64 project without needing Cygwin.

1. Install Cygwin

First, download and run either the 32- or 64-bit version of the Cygwin installer, depending on your version of Windows. Cygwin’s setup wizard will walk you through a series of steps. If your machine is located behind a proxy server, make sure to check “Use Internet Explorer Proxy Settings” when you get to the “Select Your Internet Connection” step.

When you reach the “Select Packages” step (shown below), don’t bother selecting any packages yet. Just go ahead and click Next. We’ll add additional packages from the command line later.

After the Cygwin installer completes, it’s very important to keep the installer around. The installer is an executable named either setup-x86.exe or setup-x86_64.exe, and you’ll need it to add or remove Cygwin packages in the future. I suggest moving the installer to the same folder where you installed Cygwin itself; typically C:cygwin or C:cygwin64.

If you already have Cygwin installed, it’s a good idea to re-run the installer to make sure it has the latest available packages. Alternatively, you can install a new instance of Cygwin in a different folder.

2. Install Required Cygwin Packages

Next, you’ll need to add several packages to Cygwin. You can add them all in one fell swoop. Just open a Command Prompt (in Windows), navigate to the folder where the Cygwin installer is located, and run the following command:

C:cygwin64>setup-x86_64.exe -q -P wget -P gcc-g++ -P make -P diffutils -P libmpfr-devel -P libgmp-devel -P libmpc-devel

A window will pop up and download all the required packages along with their dependencies.

At this point, you now have a working GCC compiler on your system. It’s not the latest version of GCC; it’s whatever version the Cygwin maintainers chose as their system compiler. At the time of writing, that’s GCC 4.8.3. To get a more recent version of GCC, you’ll have to compile it yourself, using the GCC compiler you already have.

3. Download, Build and Install the Latest GCC

Open a Cygwin terminal, either from the Start menu or by running Cygwin.bat from the Cygwin installation folder.

If your machine is located behind a proxy server, you must run the following command from the Cygwin terminal before proceeding – otherwise, wget won’t work. This step is not needed if your machine is directly connected to the Internet.

export http_proxy=$HTTP_PROXY https_proxy=$HTTP_PROXY ftp_proxy=$HTTP_PROXY

To download and extract the latest GCC source code, enter the following commands in the Cygwin terminal. If you’re following this guide at a later date, there will surely be a more recent version of GCC available. I used 4.9.2, but you can use any version you like. Keep in mind, though, that it’s always best to have the latest Cygwin packages installed when building the latest GCC. Be patient with the tar command; it takes several minutes.

wget http://ftpmirror.gnu.org/gcc/gcc-4.9.2/gcc-4.9.2.tar.gz
tar xf gcc-4.9.2.tar.gz

That will create a subdirectory named gcc-4.9.2. Next, we’ll configure our GCC build. As the GCC documentation recommends, it’s best to configure and build GCC in another directory outside gcc-4.9.2, so that’s what we’ll do.

mkdir build-gcc
cd build-gcc
../gcc-4.9.2/configure --program-suffix=-4.9.2 --enable-languages=c,c++ --disable-bootstrap --disable-shared

Here’s a description of the command-line options passed to configure:

  • The --program-suffix=-4.9.2 option means that once our new GCC is installed, we’ll run it as g++-4.9.2. This will make it easier for the new GCC compiler to coexist alongside the system GCC compiler provided by Cygwin.
  • The --enable-languages=c,c++ option means that only the C and C++ compilers will be built. Compilers for other languages, such as Fortran, Java and Go, will be excluded. This will save compile time.
  • The --disable-bootstrap option means that we only want to build the new compiler once. If we don’t specify --disable-bootstrap, the new compiler will be built three times, for testing and performance reasons. However, the system GCC compiler (4.8.3) provided by Cygwin is pretty recent, so --disable-bootstrap is good enough for our purposes. This will save a significant amount of compile time.
  • The --disable-shared option means that we don’t want to build the new standard C++ runtime library as a DLL that’s shared with other C++ applications on the system. It’s totally possible to make C++ executables work with such DLLs, but it takes care not to introduce conflicts with C++ executables created by older or newer versions of GCC. That’s something distribution maintainers need to worry about; not us. Let’s just avoid the additional headache.
  • By default, the new version of GCC will be installed to /usr/local in Cygwin’s virtual filesystem. This will make it easier to launch the new GCC since /usr/local/bin is already listed in Cygwin’s PATH environment variable. However, if you’re using an existing Cygwin installation, it might prove difficult to uninstall GCC from /usr/local later on (if you so choose), since that directory tends to contain files from several different packages. If you prefer to install the new GCC to a different directory, add the option --prefix=/path/to/directory to the above configure command.

We’re not going to build a new Binutils, which GCC relies on, because the existing Binutils provided by Cygwin is already quite recent. We’re also skipping a couple of packages, namely ISL and CLooG, which means that the new compiler won’t be able to use any of the Graphite loop optimizations.

Next, we’ll actually build the new GCC compiler suite, including C, C++, and the standard C++ library. This is the longest step.

The -j4 option lets the build process spawn up to four child processes in parallel. If your machine’s CPU has at least four hardware threads, this option makes the build process run significantly faster. The main downside is that it jumbles the output messages generated during the build process. If your CPU has even more hardware threads, you can specify a higher number with -j. For comparison, I tried various numbers on a Xeon-based machine having 12 hardware threads, and got the following build times:

Be warned: I encountered a segmentation fault the first time I ran with -j4. Bad luck on my part. If that happens to you, running the same command a second time should allow the build process to finish successfully. Also, when specifying higher numbers with -j, there are often strange error messages at the end of the build process involving “jobserver tokens”, but they’re harmless.

Once that’s finished, install the new compiler:

This installs several executables to /usr/local/bin; it installs the standard C++ library’s include files to /usr/local/include/c++/4.9.2; and it installs the static standard C++ library to /usr/local/lib, among other things. Interestingly, it does not install a new standard C library! The new compiler will continue to use the existing system C library that came with Cygwin.

If later, you decide to uninstall the new GCC compiler, you have several options:

  • If you installed GCC to a directory other than /usr/local, and that directory contains no other files, you can simply delete that directory.
  • If you installed GCC to /usr/local, and there are files from other packages mixed into the same directory tree, you can run the list_modifications.py script from this post to determine which files are safe to delete from /usr/local.
  • You can simply uninstall Cygwin itself, by deleting the C:cygwin64 folder in Windows, along with its associated Start menu entry.

4. Test the New Compiler

All right, let’s compile some code that uses generic lambdas! Generic lambdas are part of the C++14 standard. They let you pass arguments to lambda functions as auto (or any templated type), like the one highlighted below. Create a file named test.cpp with the following contents:

#include <iostream>

int main()
{
    auto lambda = [](auto x){ return x; };
    std::cout << lambda("Hello generic lambda!n");
    return 0;
}

You can add files to your home directory in Cygwin using any Windows-based text editor; just save them to the folder C:cygwin64homeJeff (or similar) in Windows.

First, let’s see what happens when we try to compile it using the system GCC compiler provided by Cygwin:

g++ --version
g++ -std=c++1y test.cpp

If the system compiler version is less than 4.9, compilation will fail:

Now, let’s try it again using our freshly built GCC compiler. The new compiler is already configured to locate its include files in /usr/local/include/c++/4.9.2 and its static libraries in /usr/local/lib. All we need to do is run it:

g++-4.9.2 -std=c++14 test.cpp
./a.exe

It works!

https://preshing.com/20141108/how-to-install-the-latest-gcc-on-windows/

Данный текст будет полезен тем, кто давно хотел слезть с иглы тяжеленных IDE, но настройка компилятора под себя – казалось делом неблагодарным и запутанным.

VS Code – это лишь редактор кода. Это не среда разработки – здесь нет встроенного компилятора или дебаггера. Здесь есть только их поддержка. Чем более инструмент универсален – тем сложнее вначале разобраться в его особенностях. Однако, здесь нет ничего невозможного! Если правильно один раз настроить VS Code, то вы получите замечательную среду с помощью которой можно поддерживать различные проекты на совершенно разных языках.

VS Code является легковесным, кроссплатформенным редактором кода. Одной из его главных особенностей является поддержка кучи плагинов. Плагины позволяют расширять технологию IntelliSense (автодополнение кода) на разные языки программирования, добавлять поддержку специфического оборудования, отладчиков и прочее. Очень приятная и гибкая цветовая схема не раздражает даже после многочасового просиживания в процессе работы.

В общем-то поэтому решил написать как подготовить себе приятную среду разработки. В данном случае – под C и C++

Картинки кликабельны. И их максимально много. Если считаете, что что-то слишком очевидно, то пропустите этот момент

Чаще всего используется компилятор gcc. Данный компилятор обычно идет совместно с Unix-осью. Для того, чтобы работать с этим компилятором на Windows, нужно установить некоторые инструменты разработки. Есть два больших и известных проекта, созданных с данной целью:

  • MinGW
  • Cygwin

Главное их отличие в том, что MinGW сосредоточен в основном на компиляторе с некой поддержкой системных команд, в то время как Cygwin старается эмулировать полноценную UNIX-среду.

Обсуждение на Stack Overflow на эту тему

https://stackoverflow.com/questions/771756/what-is-the-difference-between-cygwin-and-mingw

Установка MinGW

Первым делом нужно убедится, что на компьютере уже не установлен компилятор gcc. Нажмем Win+R и вызовем командную строку.

C:UsersUser> gcc -version

Если компилятор не установлен – выведется сообщение, что программа не найдена. Иначе, можно опустить установку и настройку MinGW и переходить прямо к разделу с настройкой VS Code.

Закрываем консоль (“cmd“) и переходим на официальный сайт проекта MinGW http://www.mingw.org/.

Ищем ссылку “Download” и переходим. Должно открыться что-то подобное, как на рисунке снизу.

Выбираем необходимые нам пакеты. Нам нужен базовый пакет mingw32-base и mingw32-gcc-g++. Отмечаем их

Внимание – приписка 32 в названии не означает работу приложения только и/или нацеленно на 32-битной платформе

После чего применяем внесенные изменения

Видим, что будет установлено/обновлено 24 пакета

Новое окно сообщает об успешном применении изменений

Теперь можем перейти в папку установки и убедиться в том, что все необходимое установлено (g++.exe и gcc.exe)

Выполним проверку установки переменной PATH. Проведем такую же проверку, как и в начале. Нажмем Win+R и вызовем командную строку.

Попросим компилятор вывести его версию следующей командой:

C:UsersUser> gcc -version

Если все сработало как нужно, то переходим к разделу с настройкой VS Code.

Если в консоли появилась ошибка, то нужно настроить переменную PATH. Это глобальная системная переменная и содержит в себе каталог исполняемых программ. То есть её настройка позволяет запустить программу по имени, не указывая полный путь до исполняемого файла. Их есть два вида – отдельная для каждого пользователя и одна общесистемная, которая доступна каждому пользователю.

Как настроить переменную PATH

Переходим в “Этот компьютер” и нажимаем правую кнопку -> свойства.

Далее в левой колонке жмем “Дополнительные параметры среды

Далее в “Переменные среды

Выбираем в списке переменных сред для пользователя выбираем переменную PATH и жмем “Изменить“.

Жмем “Создать” и вписываем полный путь до папки MinGWbin

Нажимаем “Ок” и снова вызываем командную строку – Win+Rcmd.

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

Выводим для проверки версию компилятора:

C:UsersUser> gcc -version

Заодно проверим дебаггер:

C:UsersUser> gdb -version

VS Code – Hellow World

Скачиваем с официального сайта абсолютно бесплатный VS Code.

https://code.visualstudio.com/

Процесс установки опустим – подсказок установщика достаточно

Для корректного автодополнения, дебага и подсказок по документации стоит установить расширение C/C++.

Расширения устанавливаются прямо из VS Code во вкладке “Extensions” или Ctrl+Shift+X. На нижней картинке эта вкладка подчеркнута в левом столбце.

Найдем через строку поиска C/C++ и установим.

Далее создаем папку будущего проекта в произвольном месте на компьютере. Свою назвал “helloworld“. Она будет папкой всего проекта, который вы будете разрабатывать. В VS Code открываем папку используя File > Open Folder…

Откроется проект. Пока он пустой. Создадим первый файл в проекте через File > New File

Чтобы VS Code начал предлагать подсказки по вводу и подсвечивать синтаксис, следует сразу после создания файла сохранить его в необходимом расширении. По сути сейчас вы определяете язык будущего проекта. Нажимаете File > Save… и в открывшемся окне выбираете тип файла. Т.к. наш тестовый проект пишется на Си, выбираем его в выпадающем списке Тип файла.

Теперь при вводе текста будут появляться подсказки с автодополнением. Для подстановки предложенного автодополнения можно нажать Tab. В VS Code достаточно много удобных хоткеев. Посмотреть все быстрые клавиши можно тут File > Preferences > Keyboard Shortcuts

Запишем наш код HelloWorld в файл. В принципе, можно писать любой код – главное, чтобы был вывод в консоль для отладки.

#include <stdio.h>

int main(void)
{
    char * msg = "Hello World";
    printf("%s", msg);
    return 0;
}

Настройка компилятора

Время перейти к настройке компилятора и дебаггера.

Компилятор позволит из написанного кода собрать рабочее приложение.

Переходим Terminal > Configure Default Build Task…

Мы изначально определили язык программирования (во время сохранения) и VS Code самостоятельно нашел компилятор – нам предложено задать сценарий работы с ним.

Если самостоятельно VS Code не нашла компилятор, то нужно редактировать файл c_cpp_properties.json, который идет вместе с расширением. Именно в данном файле настраивается путь к includePath

Подробнее по ссылке на официальном сайте. Ссылка актуальна на 2020 год.

https://code.visualstudio.com/docs/cpp/configure-intellisense-crosscompilation

Кликаем по предложенной подсказке.

Текст файла примерно такой:

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

Выглядит страшно, как и любой развернутый JSON

Гайд на официальном сайте vscode говорит о том, что этого достаточно, а если что-то идет не так, то отсылают почитать про функционал task.json. К сожалению, если оставить в таком виде, то собирать многофайловые проекты будет невозможно.

Если в вашем проекте будет НЕ больше одного файла, можете пропустить дальнейший текст и перейти к настройке дебаггера. Если планируется работать с несколькими файлами – рекомендую проделать дальнейшие манипуляции.

JSON – это текстовое представление данных/объектов (в основном в JS).
Обычно используется для передачи данных в парах Клиент-Сервер.
Массивы обозначаются квадратными скобками []
Ячейки обозначаются фигурными скобками {}
Обычная запись представляет собой пару ключ-значение через двоеточие:
{ “Ключ” : “Значение” }
Значение может быть массивом, ячейкой, массивом ячеек и т.д. – ограничений нет.

Коротко про JSON

Поле tasks содержит массив ( [массив] ), который состоит из ячеек отделенных фигурными скобками и запятыми ( [ {ячейка 1}, {ячейка 2}, {ячейка 3} ] ). В нашем случае этот массив содержит одну ячейку.

Создадим еще один элемент в массиве задач (task). Нужно скопировать все что есть в квадратных скобках (task[ вот это ]) и вставить через запятую в конце первой ячейки массива.

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

Файл должен выглядеть примерно как указано выше. Следите за скобками и запятыми – если где-то будет ошибка VS Code сообщит. Удаляем ячейку “group” на строках 20-23. Этот параметр отвечает за выбор компилятора, который будет запущен по-умолчанию.

Нас сейчас больше всего интересуют строки с 27 по 31.

Изменим значение ячейки “label” на 27 строке на любое название. Пусть будет build c project. Именно по этому имени мы сможем понять какой именно компилятор сейчас выбран.

Ячейка “command” – это команда, которая будет передана в терминал/консоль для старта компиляции. Как мы видим, все правильно, это путь к gcc.exe.

Ячейка “args” – это список аргументов, который будет передан после команды. Не пугайтесь, мы уже это делали. Чуть ранее мы узнавали версию gcc путем передачи аргумента -version.

  1. “-g” указывает компилятору на необходимость вставлять в готовое приложение отладочную информацию – номера строк, имена переменных и т.д. Необходимо для корректной работы дебаггера (отладчика) GDB;
  2. Следующим аргументом идёт файл или список файлов. “${file}” означает текущий файл. То есть компилятору будет передан только один файл. Мы хотим, чтобы сюда входили все файлы из определенной директории. Да, одним из решений будет вписывать сюда каждый созданный .c файл, но разве это удобно? Значит записываем сюда конструкцию: Из этой директории, взять все .c-файлы. Получится следующее: “${fileDirname}/**.c
  3. Аргумент вывода файла
  4. Путь вывода скомпилированного приложения.

В итоге, добавленная нами часть будет выглядеть следующим образом:

         {
            "type": "shell",
            "label": "build c project",
            "command": "C:\MinGW\bin\gcc.exe",
            "args": [
                "-g",
                "${fileDirname}/**.c",
                "-o",
                "${fileDirname}\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "C:\MinGW\bin"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

Подробнее про task.json

https://code.visualstudio.com/docs/editor/tasks

Настройка отладчика

Теперь настроим дебаггер или отладчик. Переходим в наш файл с кодом, далее Run > Add Configuration…

Выбираем окружение GDB

Выбираем Сборка и отладка активного файла

Если возникла ошибка и открылось окно, нажмите на нем Abort. Это лишь значит, что не удалось собрать приложение – может быть синтаксическая ошибка.

Далее откроется файл launch.json

Для тех, кто добавлял свой task: Изменим значение preLaunchTask на то название, которое придумали для своего компилятора. В моем случае – это “build c project“. Чтобы не было путаница стоить изменить и поле “name“. Можете как и прошлом примере добавить еще одну конфигурацию запуска в массив конфигураций, оставив первоначальную без изменений.

Запускаем приложение

Снова переходим в созданный файл с кодом и выбираем Terminal > Run Build Task…

Эта команда проведет все шаги компиляции приложения и создаст в целевой папке исполняемый файл с расширением .exe

На картинке выше красным подчеркнут выпадающий список открытых терминалов (без паники – это как несколько cmd-консолей или терминалов в линуксе). Синим (правее красной линии, видно плохо) подчеркнуты элементы управления списком терминалов – их можно добавить, удалить или поставить парочку рядом.

Как мы видим, процесс компиляции завершился без ошибок и в списке файлов проекта появился .exe.

Создадим новый терминал.

Как мы видим, изменился порядковый номер нового терминала. Также видно, что мы находимся в папке с проектом. Отсюда можно вызвать наше скомпилированное приложение. Можно начать набирать его имя и нажать Tab и сработает автодополнение. На каждое следующее нажатие терминал предложит различные подходящие варианты под то, что имелось ввиду. Если предложить нечего – ничего не произойдет.

Вызовем наше приложение. В моем случае:

> .hellowd_main.exe

Замечательно, вывод сработал как надо.

Теперь инициируем отладку/дебаггинг этого приложения, чтобы посмотреть как это работает.

Установим “Breakpoint” или точку останова. Все как в классических IDE.

Запускаем отладку Run > Start Debugging или f5

Выполнение программы было приостановлено в том месте, которое мы пометили точкой останова.

Открылось другое окно редактора, которое специально подготовлено для работы в режиме отладки. В левой части окна появилось четыре секции:

  • VARIABLES все переменные
  • WATCH сюда, через знак плюса можно добавлять переменные, функции и т.д. по имени
  • CALL STACK стек вызовов функции. В общих чертах – функции часто вызываются в теле других функций.
  • BREAKPOINTS все точки останова

Текущая выполняемая строка подсвечивается и имеет желтый указатель строки

Управление ходом отладки программы тоже удобное и классическое.

  • Продолжить
  • Сделать шаг
  • Пройти “внутрь” текущей строки
  • Выйти на уровень выше
  • Перезапуск отладки
  • Остановка отладки

Удачного освоения инструмента

MinGW, a contraction of “Minimalist GNU for Windows”, is a minimalist development environment for native Microsoft Windows applications.

Downloading MinGW

  1. open http://www.mingw.org/
  2. Click Download Button as shown in the picture below.

dowinload mingw exe

3. As soon as you click download button on mingw website   The following page will open in your browser (from the SourceForge.net web site).

mingw download page

4. The following exe file will be downloaded with the name  mingw-get-setup.exe

mingw-get-setup-exe

5. Click  mingw-get-setup.exe

6. Click install

mingw-click-install

7. Click continue

mingw-click-continue

8. Click continue

mingw-installation-manager-setup-tool

mingw-on-installation-setup-complete-click continue

9. The following pop-up window will appear. Pleas make sure that you selected all the check-boxes. e.g. mingw32-base, mingw32-gcc=g++, msys-base and so on.

mingw-check-all-options

10. Click on Installation > Apply Changes as shown in the picture below.

mingw-apply-changes

11. wait for the process to complete. once you see successful installation message close the window. Click Close.

12. Now we will set environment variable to use gcc and g++ command from terminal.

Windows 10 and Windows 8
  1. In Search, search for and then select: System (Control Panel)
  2. Click the Advanced system settings link.

select-advanced-system-settings

  • Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New.

select-environt-variables

select-path-click-edit

  • In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable.
  • Copy C:MinGWbin . 
  • Click OK.
  • Close all remaining windows by clicking OK.

set-path

  • Reopen Command prompt window, and type gcc. if you see the following output as shown in the picture below the mingw is installed successfully.

open-cmd-type-gcc


Video : How To install MinGW on Windows 10 (GCC & G++)

  • MinGW

Понравилась статья? Поделить с друзьями:
  • Как добавить webstorm в контекстное меню windows
  • Как добавить ftp сервер в windows 10
  • Как добавить батник в автозагрузку windows 10 через cmd
  • Как добавить firefox в автозагрузку в windows 10
  • Как добавить бат файл в автозагрузку windows 10