Install c compiler on windows

How to Install C and C++ Compilers on Windows

If you want to run C or C++ programs in your Windows operating system, then you need to have the right compilers.

The MinGW compiler is a well known and widely used software for installing GCC and G++ compilers for the C and C++ programming languages.

But many devs face difficulties when installing the compiler, so I am going to show you all the steps to do so in this article with screenshots to help you get it done.

I will be using Windows 11, but the same process is applicable for all other Windows operating systems unless you are using Windows XP (You need to change some steps in Windows XP).

If you’d like to watch the video I made on this topic as well, here it is:

Install MSYS2

Firstly we need to download an executable file from MSYS2. Go to the official website of MSYS2: https://www.msys2.org/. The website looks like below as of today.

Screenshot--8-

Scroll down a little bit until you find the download button for the executable file.

Screenshot--9-

Simply click on the installer button and save the installer file in any place you want.

Screenshot--10--1

Finish downloading the executable file. It should not take much time depending on your internet speed.

Screenshot--11-

After downloading the file, we will get this executable file.

Screenshot--12-

Double click on the executable file. Then click Next.

Screenshot--13-

Keep the name as it is, and click Next.

Screenshot--14--1

Keep all this as it is, and click Next.

Screenshot--15-

Give it some time to finish the installation process.

Screenshot--16-

If you keep the checkmark, then the MSYS2 terminal will open once you click Finish.

Screenshot--17-

I prefer to do it this way, but if you want to do the remaining tasks later, then you need to open the terminal by yourself from the start menu.

In that case, you have to click the start button > Search for MSYS2 and click on the terminal like in the following picture:

Screenshot--26-

Let me assume that we have opened the MSYS2 MSYS terminal successfully.

Apply the command pacman -Syu to update the package database and the base packages.

Screenshot--19-

Type Y and press the enter key if you get this type of installation prompt.

Screenshot--20-Screenshot--21-Screenshot--22-

Type Y and press the enter key.

Screenshot--23-Screenshot--24-

The terminal will be closed. We have to open the terminal manually and update the rest of the packages.

Click the start button.

Screenshot--25-

Search the folder named MSYS2 64bit. Click on the folder to expand and get the terminal. Open the terminal by clicking MSYS2 MSYS.

Screenshot--26--1

Update the rest of the packages by applying the command, pacman -Su. You might need to apply the command pacman -Sy if the terminal tells you to do that.

Screenshot--27-

If you get any installation prompt, then you need to type Y or y and press the enter key.

Screenshot--28-Screenshot--29-

Wait a little to finish the installation.

Screenshot--30-Screenshot--31-

Close the window after finishing the installation.

Install the GCC and G++ Compilers

Click the start button. Find the MSYS2 64bit folder. Click on that folder to expand it.

Screenshot--32-

If you are using a 64 bit operating system like I am, then we need to use the MSYS2 MinGW x64 terminal. Click on the terminal to open that.

Screenshot--33-

⚠️ But, if you are using a 32 bit operating system, then you have to use the MSYS2 MinGW x86 terminal. Then, you need to open that terminal.

Screenshot--34-

As I am using a 64 bit operating system, I have opened the terminal for 64 bit. Apply the command pacman -S mingw-w64-x86_64-gcc to install the compilers.

⚠️ If you are using a 32 bit operating system, then you have to apply the command pacman -S mingw-w64-i686-gcc in your 32 bit terminal.

Screenshot--35-

Wait for a little while.

Screenshot--36-

Type Y or y and press the enter key if you get the installation prompts.

Screenshot--37-Screenshot--38-

Give it some time to finish the installation process.

Screenshot--39-Screenshot--39--1

You’ve now finished installing the compilers.

How to Install the Debugger

If you are using a 64 bit operating system like I am, then you have to apply the command pacman -S mingw-w64-x86_64-gdb.

⚠️ If you are using a 32 bit operating system, then you have to apply the command pacman -S mingw-w64-i686-gdb in your 32 bit terminal.

Screenshot--41-

If you get any installation prompt, then simply type Y or y and press the enter key.

Screenshot--42-Screenshot--38--1

Give it some time to finish the installation.

Screenshot--44-Screenshot--45-

You can close the terminal.

How to Add the Directory to the Path of the Environment Variables

Open the file explorer.

Screenshot--46-

I am assuming that you have installed the MSYS into the default directory like I have. If you used custom directories, then you need to go to the directory where you installed it.

Screenshot--47-

If you are using a 64 bit operating system like I am, then go to the mingw64 folder.

⚠️ If you are using a 32 bit operating system, then go to the mingw32 folder.

Screenshot--48-

We have to go to the binary folder now. Go to the bin folder.

Screenshot--49-

⚠️ If you are using a 32 bit operating system, then you have to go into your mingw32 folder > bin folder.

Copy the directory.

Screenshot--51-

⚠️ If you are using a 32 bit operating system, and you also installed the MSYS2 in the default directory, then your directory should be like the following:

C:\msys64\mingw32\bin

Open the Advanced System Settings. You can do that in many ways. A simple way is to simply click the start button and search for it like the below screenshot.

Screenshot--52-

Click Environment Variables from the Advanced tab.

Screenshot--54-

Click on Path and select that. Then click Edit.

Screenshot--57-

A window will appear as below:

Screenshot--58-

Click New.

Screenshot--59-

A blank box will appear.

Screenshot--60-

Paste the directory here.

Screenshot--61-Screenshot--62-

Click OK.

Screenshot--63-

Click OK.

Screenshot--65-

Click OK.

Screenshot--66-

If you want to get all the steps in a video, then you can watch this video as well.

Check the Install

Now it is time to check whether we have successfully installed all of the above or not.

Open the terminal / PowerShell / CMD and apply the commands serially:

For checking the GCC version:

gcc --version

Screenshot--68-

For checking the G++ version:

g++ --version

Screenshot--69-

For checking the GDB version:

gdb --version

Screenshot--70-

Conclusion

I hope this article helps you install your compilers on the Windows operating system for C and C++ programs.

Thanks for reading the entire article. If it helps you then you can also check out other articles of mine at freeCodeCamp.

If you want to get in touch with me, then you can do so using Twitter, LinkedIn, and GitHub.

You can also SUBSCRIBE to my YouTube channel (Code With FahimFBA) if you want to learn various kinds of programming languages with a lot of practical examples regularly.

If you want to check out my highlights, then you can do so at my Polywork timeline.

You can also visit my website to learn more about me and what I’m working on.

Thanks a bunch!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Превью к статье об установке gcc на Windows

Для того, чтобы писать программы на C/C++ обычно достаточно установить какую-нибудь интерактивную среду разработки (IDE), например, Visual Studio или Eclipse, однако иногда (обычно в целях обучения студентов) требуется создавать программы в обыкновенном текстовом редакторе и компилировать приложение, используя консоль и компилятор gcc. В Unix системах он обычно установлен прямо «из коробки», а вот на Windows системах такой роскоши не наблюдается. Более того, у многих пользователей возникает множество проблем при установке компилятора. Поэтому нами было принято решение написать данную статью, чтобы помочь всем тем, кому пришлось или приходится мучаться с установкой этого компилятора на Windows.

Кстати, если вдруг на вашей Unix системе не установлен GCC, то поставить его можно командой sudo apt install gcc, введя свой пароль и согласившись на установку.

0. Прежде чем поставить компилятор GCC

Перед тем как приступить к установке этого компилятора на ваш компьютер, убедитесь в том, что GCC ещё не установлен на нём. Для этого откройте консоль (нажмите Win + R, введите в появившемся окне cmd и нажмите клавишу Enter) и введите следующую команду: gcc --version и нажмите Enter. Если компилятор уже установлен, то выполненная команда выдаст примерно следующую информацию:

gcc (GCC) 8.1.0
Copyright (C) 2018 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 (второй скриншот), значит компилятор уже установлен и больше дополнительно ничего делать не нужно. А вот если вывод командной строки такой:

"gcc" не является внутренней или внешней
командой, исполняемой программой или пакетным файлом

— значит GCC ещё не установлен в системе, поэтому двигаемся дальше.

Появившееся окно консоли

Появившееся окно консоли

GCC уже установлен

GCC уже установлен

GCC не установлен

GCC не установлен

1. Скачиваем установщик компилятора

Чтобы поставить GCC на операционную систему Windows, необходимо скачать установочный файл для него. Сделать это можно здесь: equation.com/servlet/equation.cmd?fa=fortran. Найдите в таблице версию компилятора, которая вам больше нравится (мы рекомендуем скачивать самую последнюю, на текущий момент — это версия 8.2.0) и скачайте установщик для вашей системы (32 или 64 бит).

Выбор установочного файла

Выбор установочного файла

2. Установка GCC

После того, как файл был скачан, откройте в проводнике папку, в которую был скачан установщик и запустите его, кликнув по файлу дважды левой кнопкой мыши. Появится окно, требующее подтверждения действия. В нём нужно выбрать да (иначе ничего ставиться не будет).

Установщик начнёт работу и отобразит окно с консолью, а также окно с бежевым фоном, в котором попросит прочесть и принять (или отклонить) лицензионное соглашение. Нажимаем Accept.

Открывшееся окно с установщиком

Открывшееся окно с установщиком

Принимаем лицензионное соглашение

Принимаем лицензионное соглашение

После этого установщик попросит выбрать путь для установки, предложив по умолчанию путь C:\mingw. Если вам категорически не нравится этот путь — измените его на более подходящий на ваш взгляд, в противном же случае просто нажмите Install.

Выбор папки для установки

Выбор папки для установки

Теперь остаётся только дождаться окончания распаковки архивов и установки их на компьютер. Как только все файлы будут установлены, инсталятор сообщит об этом, после чего нужно будет нажать на кнопку Finish.

Распаковка файлов и установка

Распаковка файлов и установка

Окончание установки

Окончание установки

3. Проверка установки

По завершении работы установщика перезагрузите компьютер и вновь откройте окно командной строки, введите команду gcc --version и нажмите Enter. На этот раз ответ от этой команды должен будет совпадать со вторым скриншотом из пункта 0. Если это не так, то скорее всего работа установщика была некорректно или преждевременно завершена, так что просто начните установку заново.

GCC установлен

GCC установлен

Поздравляем! Теперь на вашем компьютере установлен компилятор GCC и вы можете писать программы на языках C и C++, а компилировать их через командную строку!

4. Бонус. Компиляция программ с помощью GCC

Теперь, когда у вас установлен компилятор GCC, вы можете создавать программы на C/C++, используя только текстовый редактор и консоль. Для этого создайте новый файл и назовите его как угодно (например, hello_world). Задайте ему расширение .c вместо .txt. Напишите (или скопируйте) текст программы на С в этот файл. Откройте командную строку (Win + R, cmd) и введите следующую команду gcc hello_world.c и нажмите Enter. Если код не содержит ошибок, то результатом команды будет пустота. В противном же случае вы увидите все ошибки, который нашёл компилятор в программе с указанием места этой ошибки. При этом в проводнике появится файл a.out.exe, который будет являться исполняемым файлом для написанной программы. Чтобы запустить его введите в консоли a.out (для Unix-систем нужно писать ./a.out) и нажмите Enter.

Что ещё за a.out? Непонятно!

По умолчанию при компиляции программ GCC в качестве результата создаём исполняемый файл с именем a.out (если такой уже есть, то b.out и т.д.). Это может быть не очень удобно, если у вас в папке лежит сразу много программ, которые нужно скомпилировать и затем запустить. Неудобно хотя бы тем, что разобраться, что такое a.out, а что такое b.out и c.out может быть непросто. Именно поэтому мы рекомендуем компилировать программы с явным указанием имени выходного файла. делается это так: gcc имя_файла.c -o имя_программы.

В результате выполнения такой программы вместо a.out будет создаваться файл с именем, заданным в имя_программы. Например, если для файла hello_world.c мы хотим получить программу hello, то компилировать нужно такой командой: gcc hello_world.c -o hello.

Результат компиляции и запуска программы

Результат компиляции и запуска программы

Используя понятные имена выходных программ (исполняемых файлов), вы гарантируете себе простоту работы и сокращение времени на разбирательство спустя долгое время.

Возможно, также будет интересно: как установить Sublime Text для работы с C/C++.

Фото Перминова Андрея, автора этой статьи

Программист, сооснователь programforyou.ru, в постоянном поиске новых задач и алгоритмов

Языки программирования: Python, C, C++, Pascal, C#, Javascript

Выпускник МГУ им. М.В. Ломоносова

The definitive guide of setting up C/C++ development environment on Windows

I know a lot of you are having troubles of getting it to work on Windows and complaining a shiton.
I will admit, that most C++ programming books do NOT actually tell you how to set things up.
And I think that’s hilarious, because how are you supposed to program without a working development environment?
Although some books do mention it, they usually target Unix operating systems.

You can just use Visual Studio, which is the best and beginner-friendly solution and has really good documentation from Microsoft, but for some reason you are just a boomer and don’t want to use it and you are dumb to set up the alternatives.

Now, you have found the right guide!
This guide aims to provide the fullest list of every possible main-stream IDEs/text editors you might want to use and its respective configuration on Windows.

Follow the guide and screenshot carefully.
The screenshot are from Windows Sandbox, which is a clean install of Windows 10.
If you followed everything, and can’t get it work, open an issue. Let me see how that’s even possible!!

A visual summary of this guide:

flowchart TD
    A[Start]
    A-->Compiler{Compiler}
    A-->VisualStudio
    Compiler-->MSYS2{MSYS2}
    MSYS2--->GCC
    MSYS2--->Clang
    Compiler-->MSVC

    GCC-->CMake
    Clang-->CMake
    MSVC-->CMake

    CMake-->IDE{IDE}
    IDE-->VisualStudio
    IDE-->QtCreator
    IDE-->CLion

    CMake-->Editor{Text Editor}
    Editor-->Vim
    Editor-->VSCode[Visual Studio Code]
    
    GTest[Google test & Doxygen]-. integrate .->VisualStudio
    GTest[Google test & Doxygen]-. integrate .->VSCode
    GTest[Google test & Doxygen]-. integrate .->CLion
    GTest[Google test & Doxygen]-. integrate .->CMake

    subgraph tooling
    Additional[Additional tooling]---ReSharper
    Additional---ClangTidy
    Additional---ClangFormat
    Additional---Incredibuild
    end


  • The definitive guide of setting up C/C++ development environment on Windows
    • Setting up development environment
      • Download & Install a C++ compiler
        • GCC & Clang
          • Download & Install MSYS2
          • Install GCC
          • Install Clang
          • What is MSYS2 and Why?
          • What’s the difference between /usr/bin and /mingw64/bin
        • MSVC
      • Download & Install CMake
        • What is CMake and Why?
      • IDEs
        • Setting up CLion
        • Setting up QT creator
        • Setting up Visual Studio
          • Full package
          • Standalone IDE
      • Text editors
        • Setting up VSCode
        • Setting up Vim
          • Using MSYS2
          • Standalone
          • Optional plugins
    • Debugging
      • Debugging in VSCode
      • Debugging in CLion
      • Debugging in Visual Studio
      • Debugging in QT
    • Using libraries
      • Setting up vcpkg
      • Finding and Installing a library
      • Using a library
    • Unit Testing
      • Google Test
        • Integration with Visual Studio
        • Integration with CLion
        • Integration with VSCode
      • Microsoft Unit Test
      • CTest
    • Documentation
      • Setting up doxygen
      • Integrate doxygen with CMake
    • Source control
    • Setting up a system-wide package manager
      • Winget
      • Chocolatey
      • Scoop
    • Setting up WSL
    • Addtional Tooling
      • Resharper
      • Clang-tidy
        • Integration with Visual Studio
          • MSBuild Project
          • CMake Project
        • Integration with CLion
        • Integration with VSCode
      • ClangFormat
        • Integration with Visual Studio
        • Integration with VSCode
      • Incredibuild
      • C/C++ include guard (proud contributor)
      • include-info (proud maker)
      • VSCode Font switcher (proud contributor)

Setting up development environment

This section describes the steps to

  1. Download & Install a C++ compiler
  2. Download & Install CMake
  3. Download & Install an IDE/text editor
  4. Create a project in various IDEs/text editors and start writing code

Download & Install a C++ compiler

This guide will cover the installation of GCC, Clang and MSVC.

GCC & Clang

Download & Install MSYS2

Download here

Just launch the installer and keep clicking «Next»

Install GCC

If you also want to install clang, skip this part and go directly to Install Clang, because GCC is a dependency of Clang (on MSYS2) and will be automatically installed when you install clang.

  1. Run MSYS2, type the following command:

pacman is the package manager used by MSYS2. -S means «sync». -y means «download fresh package databases from the server». -u means «upgrade installed packages».

This command will update the packages info, so you get the latest packages. It will prompt you like this, and you type y and hit enter.

  1. Then it will prompt you To complete this update all MSYS2 processes including this terminal will be closed. Confirm to proceed [Y/n], type y and hit enter, and it will close the window after the update is done.
  2. Relaunch MSYS2 from your start menu. Type:
pacman -S mingw-w64-x86_64-gcc

like this, type y and hit enter to install gcc

And then type:

pacman -S mingw-w64-x86_64-make

And type y to also install make.

And then type:

pacman -S mingw-w64-x86_64-gdb

And type y to also install gdb.

  1. Now search for environment variable and open it

  2. Click Environment Variables, find Path in System variables, double click to open the setting.

  3. Click New and copy C:\msys64\mingw64\bin to the new entry.

  4. Click OK to close all windows. Now you finished installing GCC. Open any shell such as cmd and type in gcc --version and you shall see the following:

Install Clang

Installing Clang will also automatically install GCC (on MSYS2).

  1. Run MSYS2, type the following command:

pacman is the package manager used by MSYS2. -S means «sync». -y means «download fresh package databases from the server». -u means «upgrade installed packages».

This command will update the packages info, so you get the latest packages. It will prompt you like this, and you type y and hit enter.

  1. Then it will prompt you To complete this update all MSYS2 processes including this terminal will be closed. Confirm to proceed [Y/n], type y and hit enter, and it will close the window after the update is done.

  2. Relaunch MSYS2 from your start menu. Type:

pacman -S mingw-w64-x86_64-clang mingw-w64-x86_64-clang-tools-extra

like this, type y and hit enter to install clang

And then type:

pacman -S mingw-w64-x86_64-make

And type y to also install make.

And then type:

pacman -S mingw-w64-x86_64-gdb

And type y to also install gdb.

  1. Now search for environment variable and open it

  2. Click Environment Variables, find Path in System variables, double click to open the setting.

  3. Click New and copy C:\msys64\mingw64\bin to the new entry.

  4. Click OK to close all windows. Now you finished installing clang. Open any shell such as cmd and type in clang --version and you shall see the following:

(9. Optional): If you want to get clang’s implementation of the C++ standard library (ie. the STL), type this command:
pacman -S mingw-w64-x86_64-libc++
When invoking clang++, add the flag -stdlib=libc++.
The header files of libc++ will be stored at C:\msys64\mingw64\include\c++\v1.

Note: Clang and GCC is installed to the same directory, eg. under C:\msys64\mingw64\bin. Don’t be confused by the directory C:\msys64\clang64. It is an empty folder.

What is MSYS2 and Why?

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

But basically, we use its implementation of MingW(Minimalist GNU for Windows), which is a collection of common developing tools seen on GNU/Linux operating systems.

Warning
Please DO NOT follow this guide on Vscode’s official tutorial, because the Mingw-w64 project provides an out-dated GCC toolchain.

MSYS2 (in this guide) is actively maintained and provides an up-to-date GCC toolchain as well as many others, is the prefered choice.

What’s the difference between /usr/bin and /mingw64/bin

Copied from this stackoverflow answer

The GCC compiler in /usr/bin produces executables that use msys-2.0.dll as a runtime dependency. That DLL is basically a fork of Cygwin, and it provides emulation of POSIX commands not normally available on Windows. That environment is mainly for running programs from the Linux world (like bash) which need POSIX commands and cannot be easily ported to a native Windows environment.

The GCC compilers in /mingw32/bin and /mingw64/bin produce native Windows executables targeting the 32-bit or 64-bit versions of Windows respectively. The 32-bit executables can actually run on 32-bit or 64-bit Windows. These executables are easier to distribute; you generally just copy all the DLLs that they depend on from the /mingw*/bin folder to the same directory as your executable, and then you have something that will run successfully on other computers. Since the main purpose of MSYS2 is to help write native Windows software, you’ll find a much wider variety of libraries in the MinGW environments than in the msys-2.0.dll environment.

MSVC

MSVC is Microsoft Visual C++ compiler. And you know what? You do NOT have to install Visual Studio in order to get MSVC. However, if you also want Visual Studio, skip to setting up visual studio directly.

  1. Download MSVC, select Build Tools for Visual Studio 2019
  2. Launch the installer and select these workflows
  3. You have finished installing MSVC. Click Launch and type cl and you should see this:

Do NOT try to add MSVC directly to system PATH because each compiler toolchain for different architecture has its own version.

This command prompt is specific to 64bit Windows architecture and has set some temporary environment variables. You can find it in Start -> Visual Studio 2019 -> Developer Command Prompt for VS 2019 like this:

After MSVC is installed, cmake can detect it as a compiler.

Download & Install CMake

You can either install CMake by using the official installer or using a package manager like MSYS2,
which you used to install GCC and Clang.

  • Using the installer:
    1. Download here, choose the Windows win64-x64 Installer option

    2. Launch the insatller, when you see this screen, choose Add CMake to the system PATH for all users

      Now you finished installing cmake.

  • Using MSYS2:
    1. Run MSYS2 and type this command and type Y to install
    pacman -S mingw-w64-x86_64-cmake
    
    1. Search for environment variable and open it -> Environment Variables, find Path in System variables, double click to open the setting -> click New and copy C:\msys64\usr\bin to the new entry.

What is CMake and Why?

CMake is a cross-platform build-system generator, which generates build files (some files dictating how your source files should be built) for your platform.

For example, on Windows by default, it generate Visual Studio Solutions (which is some files dicating how your source files should be built, native to Visual Studio) if you have Visual Studio installed. On Linux by default, it generates Unix Makefiles (which is some files dictating how your source files should be built, native to make).

And because:

It is a bug if your C/C++ project does NOT provide CMake support.

In reality, some of the most loved IDEs/text editors really just provide good CMake support out-of-the-box. So don’t argue that Meson is better or some nonsense. To be considered «better», you really have to get good tool chain support.

IDEs

This guide will cover setting up Visual Studio, CLion, QtCreator, Cevelop (based on Eclipse) and Eclipse.

Setting up CLion

  1. Download clion

  2. Launch the installer, keep clicking «Next». When you see the following screen, I strongly recommend you to select Add "Open Folder as Project".

  3. Run clion, set up the appearance as you like, login your account or free trial.

  4. After those, it will prompt this window for setting up compilers, it should be all correct and no need to change.

  5. Create a new C++ executable or C executable on the left

  6. Clion will auto generate a «Hello world» project and everything should be working.

Setting up QT creator

  1. Download QT installer here
  2. Launch the installer and you will need to either sign in or create a qt account
  3. When you see this, click Custom Install.
  4. When you see this, click Deselect All, because we only intend to use it as a standalone IDE, aka Qt Creator. If you want to do Qt development, select the component to your need.
  5. After the installation, run Qt Creator -> New File or Project -> Non-Qt Project -> Plain C++ Application (this actually doesn’t matter, you can always change to a C application in the CMakeLists.txt file) -> Choose CMake as the build system -> select all kits (this will include the different build types in CMake). Qt Creator should create a simple «Hello world» program for you, like this:




  6. Click the Run button, and it should run

Note: If there is error during CMake’s configure, go to Tools -> Options -> Kits -> Desktop(default), and make sure the C and C++ compiler is in C:\msys64\mingw64\bin instead of C:\msys64\usr\bin.

If you installed Clang you shall see it in the compiler selection menu:

Setting up Visual Studio

You can install Visual Studio as a standalone IDE or as a whole package including compiler, toolchain and windows sdk.

Full package
  1. Download Visual studio. Choose the Community option.

  2. Run the installer, select these workflows

  3. After installation, you are prompt to restart your computer. And then you will need to register a Microsoft Account to continue using Visual Studio.

  4. Run Visual Studio, select Create a new project -> Empty Project/Console App, and select Place solution and project in the same directory.



    The only difference between Empty Project and Console App is the latter will provide you with a «Hello world» program and that’s it! All the default include directories and default linked runtime libraries are the same!

  • If you choose to create Empty Project, right click on the <Project Name> -> Add -> New item -> C++ source file -> Add, like this:


    Then write a simple «Hello world» program and hit ctrl+f5 to compile and run it, and you shall see this:

  • If you choose to create Console App, you shall see the already created «Hello world». Hit ctrl+f5 to compile and run the program and you shall see this:

Standalone IDE

If you install Visual Studio as a standalone IDE without installing MSVC compiler toolchains, you can use it with CMake. If you have installed MSVC compiler toolchain, you can use it with Visual Studio solution just as it’s a full install like above. Here I introduce how to use it with CMake, without MSVC.

  1. Download Visual studio. Choose the Community option.

  2. Run the installer, select these workflows and deselect all the optionals on the right, like this

  3. After installation, you need to register a Microsoft Account to continue using Visual Studio.

  4. Run Visual Studio, select Create a new project -> CMake Project -> select Place Project under the same directory -> Create, like this:


  5. Visual Studio will auto generate a «Hello world» project for you, and it can successfully configure the project and compile because CMake can detect the installed GCC. However, it will have incorrect include errors.

  6. To solve this error, click on the configuration menu -> Manage Configurations -> click the add button -> select Mingw64-Debug -> click on the previous old configuration and click delete button


  7. Hit ctrl+s to save this configuration, then the include error should go away.

Note: If for some reason, Visual Studio doesn’t detect the right MingW version, you will still get include errors. You need to edit the CMakeSettings.json and correct the MingW version, like this:

Text editors

Setting up VSCode

  1. Download vscode

  2. Launch the installer, when you see this screen, I strongly recommend you follow this setting

  3. Run vscode, in the extension tab, search and install the following extensions

  1. Go to settings, search generator. And set Cmake:Generator to MinGW Makefiles, like this:

  2. Create a folder, open it in vscode. Use ctrl + shift + p to open the command menu, type cmake and choose CMake: Quick Start, like this:

  3. The cmake tool will scan the kits and there will be 2 kits. Select the first one.

  4. Type a name for your project, select Executable, CMake tool will automatically generate a helloworld project for you. And you probably don’t want to enable ctest for now, so delete everything excpet the following 3 lines:

Rememeber to click Allow when cmake want to configure the intellisense.

  1. And now you can run it and debug it, and have everything working (syntax highlighting, auto complete, header files…).


Setting up Vim

Using MSYS2
  1. If you install vim in MSYS2, your .vimrc file should be placed in
    C:\msys64\home\<UserName>\.vimrc
    
  2. Create new folders along this path
    C:\msys64\home\<UserName>\.vim\autoload
    

    and then open powershell here.

  3. Type the following command to install vim-plug, a simple vim plugin manager
    iwr -useb https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim |`
        ni plug.vim -Force
    
Standalone

Download and install Vim here. It can be installed by keep clicking «Next» in the installer. (Note: Recommended method to install vim is through a package manager, see here)

  1. Install vim-plug
iwr -useb https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim |`
    ni $HOME/vimfiles/autoload/plug.vim -Force

Open .vimrc, add these following lines:

filetype plugin indent on
set tabstop=4 " show existing tab with 4 spaces width
set shiftwidth=4 " when indenting with '>', use 4 spaces width
set expandtab " On pressing tab, insert 4 spaces
syntax on
set nu " Enable line numbers 
set smartindent

call plug#begin('~/.vim/plugged') " List all the plugins to be installed

Plug 'neoclide/coc.nvim'

call plug#end() " End of plugins
  1. Install coc-clangd, the C++ language client extension

    Open whatever C++ file, and type command :CocCommand clangd.install

  2. Install clangd, the actual C++ language server.

    Type command :CocCommand clangd.install.

  3. Now you should have auto-complete working.

Optional plugins

All the plugins listed below can be installed by adding Plug '<plugin-repo>' betweeen the call plug and call plug lines in the .vimrc file.

  1. vim-airline
    An enhanced status line.
Plug 'vim-airline/vim-airline'
Plug 'vim-airline/vim-airline-themes' 


2. nerd-tree
A file explorer.

Plug 'preservim/nerdtree'
Plug 'Xuyuanp/nerdtree-git-plugin'
Plug 'tiagofumo/vim-nerdtree-syntax-highlight'
Plug 'ryanoasis/vim-devicons'

  1. startify
    A welcome screen for quick opening recent folders and projects

    Plug 'mhinz/vim-startify'


Debugging

This section describes how to debug in various IDEs/text editors.

Debugging in VSCode

To launch the debugger in VSCode, click the cmake project menu -> right click on the <target name> -> Debug like this:

See more documentation for VSCode’s debugging UI here, except for the part that sets launch.json because the CMake tools already handles everything :)

Debugging in CLion

Click here

For more, see documentation here

Debugging in Visual Studio

Click here

For more, see documentation here

Debugging in QT

Click here


Using libraries

Setting up vcpkg

vcpkg is a C/C++ package manager, which makes using libraries much easier (almost as easy as using pip in python).

You HAVE TO install MSVC or Visual Studio on Windows to use vcpkg.
(Mingw GCC CAN NOT be used to build vcpkg on Windows at the time being).
After MSVC is installed, you can follow the guide here
to set it up.

Starting from this commit, vcpkg binary can be
directly downloaded by running bootstrap-vcpkg.bat, you no longer need to install MSVC to build it!

  1. Open a shell(cmd) and go to the directory where you want vcpkg to be installed. (Something like C:\ or C:\dev)
  2. Type this command:
    git clone https://github.com/microsoft/vcpkg
    
  3. Type this command:
    .\vcpkg\bootstrap-vcpkg.bat
    
  4. Type this command:
    .\vcpkg\vcpkg.exe integrate install
    

Finding and Installing a library

  • To find a library, use vcpkg search <library>
  • To install a library, use vcpkg install <library>:x64-windows or vcpkg install <library>:x86-windows

Note
vcpkg will build 32 bit libraries by default on Windows (although it’s 64 bit on Linux by default,Microsoft fix it please), which is NOT probably what you want, so you want to speficy the architecture by adding :x64-windows.

Using a library

After you install the library in vcpkg, you either:

  • Use Visual Studio without ANY ADDITIONAL CONFIGURATION
  • Use cmake with the instruction provided by vcpkg when you install the library.

Below is a complete example of using vcpkg to install and use the boost library.

  1. Install the library in vcpkg with vcpkg install <Library Name>, like this:

    vcpkg install boost:x64-windows
    

    And you should see the following

  2. Note that on Windows, vcpkg builds libraries using MSVC, so you should also use MSVC in order to link sucessfully. Header-only libraries like boost may be used with other compilers like GCC.

Afrer the library finishes installing, you can either:

  • Use it in Visual Studio without doing any additional configuration

    Note: Configure the solution achitectural target correctly according to your library. Visual Studio empty project defaults to x86 but you may installed x64 library.

  • Or use it in VSCode/CLion with cmake and cmake tool chain file. See the docs here


Unit Testing

What is unit testing?

Google Test

google test is a famous and widely supported by IDEs/text editors unit testing framework for C++.

You can get google test by these ways

  • Using vcpkg: Following setting up vcpkg, we can easily install the library by

    vcpkg install gtest:x64-windows
    

    Note that if your application is targeted to 32 bit, use this command instead

  • Using MSYS2: Note that this can only be used with GCC & Clang compiler from MSYS2.

    pacman -S pacman -S mingw-w64-x86_64-gtest
    

After installing the library,

  • If you use Visual Studio (MSBuild Project), you just need to #include <gtest/gtest.h> like a normal C++ source file and either:

    • Provide a main function at the bottom of your source file

      int main(int argc, char **argv) 
      {
          ::testing::InitGoogleTest(&argc, argv);
          return RUN_ALL_TESTS();
      }

    • Don’t provide a main function, then you need to link additional libraries in the linker settings.

      1. Right click on your project -> Properties -> Linker -> AdditionalDependencies,
        Make sure this configuration is Debug and x64
        (or x86 depend on the architect or your installed Gtest library)
        and add these 2 lines
      gtestd.lib
      $(VcpkgRoot)installed\$(VcpkgTriplet)\debug\lib\manual-link\gtest_maind.lib
      

      1. Click the configuration menu to Release and also add these 2 lines, like this
      gtest.lib
      $(VcpkgRoot)installed\$(VcpkgTriplet)\lib\manual-link\gtest_main.lib
      

      Then you should be able to write the test source file without the main function, and build in both configurations like this

  • If you use CMake, regardless of whether you installed Google Test library from vcpkg or MSYS2,
    you can make use of CTest built-in to Cmake as a test runner to run your google test,
    which is supported by most IDE/editors you will see below.
    A minimum CMakeLists.txt is like:

cmake_minimum_required(VERSION 3.10.0)

project(<project name> VERSION 0.1.0)

find_package(GTest CONFIG REQUIRED)
enable_testing()
include(GoogleTest) #for gtest_discover_tests() function

add_executable(<test target name> test.cpp) #This is the testing executable
target_link_libraries(<test target name> PRIVATE GTest::gtest GTest::gtest_main) #Link it to the google test library
gtest_discover_tests(<test target name>)  #integrate google test with ctest to this testing executable
  • Or you simply want a testing executable, so you don’t bother with CTest.
cmake_minimum_required(VERSION 3.10.0)

project(<project name> VERSION 0.1.0)

find_package(GTest CONFIG REQUIRED)
add_executable(<test target name> test.cpp) #This is the testing executable
target_link_libraries(<test target name> PRIVATE GTest::gtest GTest::gtest_main) #Link it to the google test library

Integration with Visual Studio

Integration with CLion

CLion has test adaptors built-in so it should automatically detect the test whether you are using CTest as runner or just simply compiling a testing executable.

You can click the run button on the left of each TEST() macro to run individual test, or click ctrl+shift+f10 to run all test.

See here for more documentation.

Integration with VSCode

You need to use CTest (the first version of the minimum CMakeLists.txt) as your test runner to get the integration working.

  1. Install the CMake Test Explorer extension (proud contributor)
  2. Open VSCode settings, go to Extension -> CMake Test Explorer section, and change these following settings:
    • Build Config: ${buildType}
    • Build Dir: ${buildDirectory}
    • Select Cmake Integration
  3. After that, build your project once and then click the refresh test button, this plugin should find all the testing suites and test cases in your test files.
  4. Then you can easily manage or debug all your test cases or each individual test in this panel.

Microsoft Unit Test

CTest

Documentation

Setting up doxygen

Writing good documentation is also an essential part of development. The most commonly used documentation generator is doxygen. Download the binary distribution for Windows and then install it. After it is installed, there will be a GUI frontend called doxywizard, which looks like this:

To write good documentation, install these plugins:

  • For VSCode (proud contributor)
  • For Visual Studio

Learn the syntax for documentation here

After you documment your code, any decent IDEs/text editors should be able to show the documentation, helping you better understand your own code as well as others.

Using doxygen is straight-forward using the GUI, just specify the root directory of your project, configure some settings to your liking, then run it.

Doxygen generated documentation too ugly?
Follow the guide here
to use doxygen with sphinx for a more beautiful documentation.

Integrate doxygen with CMake

You can set up an automatic documentation generation step within CMake, so that each time you build your cmake project,
the docs would be generated or updated.
To do that, assuming you have a doc directory in your project, something like this

MyProject
|--doc
|--README.md
|--CMakeLists.txt
|...

add the following snippet to your root CMakeLists.txt

find_package(Doxygen)
if(DOXYGEN_FOUND)
    set(DOXYGEN_USE_MDFILE_AS_MAINPAGE "${CMAKE_SOURCE_DIR}/README.md")
    set(DOXYGEN_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/doc")
    set(DOXYGEN_EXCLUDE_PATTERNS "<your binaries or other files generated by your IDE>")
    doxygen_add_docs(doc ${CMAKE_SOURCE_DIR} ALL) #this will create a target called "doc"
    #You can either manually run the target or it will automatically run when "cmake --build ." is called
endif()

Source control

Most if not all of the development workflow involves using Git.
Also, some of CMake’s functionalities requires Git to be installed.
And you also need Git to install vcpkg.
You can install Git either by using the installer or using a package manager,
like MSYS2 which we just used above to install GCC and Clang.

  • Install by using the installer
    1. Download the installer here and then it can be installed by keep clicking Next.
  • Install by using a package manager
    • chocolatey: choco install git
    • scoop: scoop install git
    • winget: winget install git

Setting up a system-wide package manager

Package manager makes it easier to install and update softwares,
allowing you to use one single command to update all installed softwares.

On Windows, there is built-in winget on a reasonably new build of Windows 10.

I recommend installing those frequently updated software that doesn’t have a built-in updater
(like cmake, vim…)
using a package manager.

Winget

Install and docs here

Chocolatey

Install and docs here

Scoop

Install and docs here


Setting up WSL

Setting up WSL is the same as setting up a pure linux environment, therefore it is not discussed here.


Addtional Tooling

Resharper

is a non-free extension for Visual Studio that can greatly benefit your productivity. Download here.

Clang-tidy

Clang-tidy is a C++ «linter» that provides extra warnings and style checks to your C++ compiler.

Integration with Visual Studio

Clang-Tidy support is available starting in Visual Studio 2019 version 16.4.
It’s included automatically when you choose a C++ workload in the Visual Studio Installer.
More info.

MSBuild Project
  1. Right click on project -> Properties -> Code Analysis -> Clang-tidy
  2. In Checks to Enable or Disable, you can configure checks to be enabled or disabled using supported flags.
    To enable a check, add the flag name directly. To disable a check, prefix with a -.
    Flags are separated by comma.
    For example: * enables all checks.
    -clang-analyzer-* disables all checks named clang-analyzer....
  3. Build your project, and you should see warnings provided by clang-tidy.
CMake Project
  1. Click on build configuration menu -> Manage Configuration -> Edit JSON
  2. Add a key named enableClangTidyCodeAnalysis and set value to true.
    Optionally control which checks to be enabled or disabled by adding a key named clangTidyChecks
  3. Save and exit. Now you should see warnings provided by clang-tidy.

Integration with CLion

Integration with VSCode

Install this plugin.

ClangFormat

ClangFormat is a code formatting tool to help your code follow some pre-defined formatting rules.

In all IDE/editors, the actual ClangFormat executable needs to be installed first.

Integration with Visual Studio

  1. Install this plugin at the bottom «Visual Studio plugin installer»
  2. Then you can find settings in Tools -> Options -> LLVM/Clang -> ClangFormat

Integration with VSCode

ClangFormat is supported by VSCode C++ extension out-of-the-box.
ClangFormat settings can be found in C++ extension settings.

Incredibuild

is a free-for-personal-use build tool that accelerate visual studio’s project building.
It also provides a nice graph to visualize the building process and time consumption of individual files.

incredibuild

It can be installed when installing visual studio.
Download the license here.

C/C++ include guard (proud contributor)

is a VSCode extension that automatically add include guard for you so that you no longer need to remember it.
Download here.

include-info (proud maker)

is a VSCode extension that shows the included header file size
and provide a fast way to jump to those included files.
Download here

VSCode Font switcher (proud contributor)

is a VSCode extension that provide a fast way to switch between different fonts.
Download here.

Прежде чем
двигаться дальше, нам нужно настроить рабочее место для написания программ на
Си. А, именно, установить (если его еще нет) компилятор и интегрированную среду
разработки для написания, компиляции и отладки программ. Начнем с выбора и
установки компилятора. На сегодняшний день одним из самых популярных является
компилятор gcc. Это сокращение
от:

GNU Compiler Collection

Если вы
работаете под ОС Linux, то, этот компилятор должен быть уже
установлен в системе. Если же вы работаете под ОС Windows, то компилятор
нужно устанавливать самим. Давайте это сделаем.

Так как я
работаю под ОС Windows, то буду показывать порядок установки
всех средств именно на этой ОС. Итак, первым делом нужно перейти на официальный
сайт компилятора gcc, предназначенных для ОС Windows:

https://gcc.gnu.org

Далее, переходим
в раздел Download/Binaries (бинарники) и
видим несколько вариантов способов установки gcc на систему. Наиболее
удобный, на мой взгляд, является использование, так называемого, порта MinGW с установкой
только необходимых (минимального набора) компонент компилятора gcc.

Здесь есть два
варианта MinGW: старый
32-битный и новый – 64-битный. Я рекомендую воспользоваться старым вариантом,
т.к. он хорошо себя зарекомендовал и, что называется, проверен временем. С
новым могут возникать проблемы, да и для языка Си стандарта C99 он явно
избыточен.

Нажимаем на
ссылку MinGW и нас
перенаправляют на страницу:

https://osdn.net/projects/mingw/

и здесь нам
нужно скачать установщик mingw-get-setup.exe.

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

Нажимаем здесь
кнопку «Install». В следующем
окне соглашаемся со всеми настройками по умолчанию, в том числе и с маршрутом
распаковки «C:\MinGW» (если вас он
не устраивает, то можете изменить на свой) и нажимаем на кнопку «Continue». Начнется
скачивание и установка. После установки этот инсталлятор автоматически
запустится:

В диалоговом
окне нам нужно выбрать все необходимые компоненты для установки компилятора gcc для языка Си. Они
следующие:

  • mingw32-gcc-bin (после отметки
    также дополнительно отмечаются другие компоненты, с которыми mingw32-gcc-bin работает
    совместно);

  • mingw32-gcc-g++-bin (для установки
    линкера для компилятора Си);

  • mingw32-make-bin;
  • mingw32-gdb-bin (дебаггер, для
    отладки кода).

После этого в
меню «Installation» выбираем пункт
«Apply Changes» и в окне
нажимаем кнопку «Apply»:

Начнется
установка выбранных компонент для компилятора gcc в указанный
каталог.

Далее, нужно
прописать в системе путь к каталогу компилятора gcc. Для этого
нажимаем правую кнопку мыши на кнопке «Пуск» и выбираем «система». В
появившемся диалоговом окне щелкаем на «Дополнительные параметры системы», и
затем «Переменные среды…». Появится еще одно диалоговое окно, в котором нас
будет интересовать системная переменная Path:

Два раза щелкаем
по строчке с переменной Path, появится следующее окно, в котором
следует добавить путь «C:\mingw\bin» в переменную Path.

Все, компилятор gcc установлен в ОС Windows и готов к
работе. Чтобы в этом убедиться, откроем командное окно (комбинация Win+R, набираем cmd и кнопка «OK»), набираем в
нем gcc и должны
увидеть следующие строчки:

Если у вас все
отображается именно так, то компилятор был успешно установлен.

Установка и настройка Visual Studio Code

Следующим шагом
нам нужно установить интегрированную среду для написания, компиляции и отладки
наших программ написанных на языке Си. Для этого, на мой взгляд, удобно
воспользоваться программой Visual Studio Code, доступной на
странице официального сайта:

https://code.visualstudio.com

Именно в ней я
буду писать и показывать все тексты программ данного курса. При желании, вы,
конечно, можете использовать любую другую среду, главное, чтобы в ней было
удобно компилировать и отлаживать программы на Си.

Первым делом,
конечно же, нужно скачать дистрибутив программы Visual Studio Code и установить
себе на компьютер. Ничего сложно в этом нет. Далее, открываем эту программу.
Для начала работы нам нужно определиться, где будут располагаться файлы
текущего проекта. Делается это очень просто. На диске в любом желаемом месте
создается папка, которая, затем, выбирается в программе VS Code. В моем случае
– это путь:

D:\Visual
Studio\Code\course

У вас может быть
любой другой. Сейчас каталог пустой. Поэтому для начала работы в него нужно
поместить файл, в котором будем писать текст программы. Например, его можно
назвать так:

lessons.c

Обратите
внимание, файл с текстом программы на языке Си должен иметь расширение «c». Теперь здесь
можно написать простую программу. Пусть это будет классический «Hello, world!»:

#include <stdio.h>
 
int main(void) 
{
    printf("Hello, world\n");
    return 0;
}

Не беспокойтесь
пока о том, что содержимое этой программы вам, возможно, непонятно. Ее мы
подробно еще будем разбирать. Пока, на этом этапе, нам нужно просто настроить
среду разработки для компиляции и запуска программ на Си.

По идее, мы уже
сейчас можем достаточно просто скомпилировать эту программу. Для этого нажимаем
Ctrl + ~, появится
окно powershell и в нем вручную
можно вызвать компилятор gcc следующим образом:

gcc lessons.c

Если мы все
сделали правильно, то в текущем каталоге появится исполняемый файл a.exe, который
выводит в консоль сообщение «Hello, world!»:

.\a

Конечно,
постоянно выполнять компиляцию через терминал очень неудобно, поэтому нам нужно
настроить редактор VS Code под компиляцию
Си-программ. Для этого необходимо установить некоторые полезные расширения (extensions). Щелкаем слева
на кнопку с квадратиками и в поиске набираем «c lange»:

Выбираем первый
компонент C/C++ компании Microsoft, которая
позволяет выполнять разработку программ на языке Си.

После этого,
слева щелкаем на кнопку с треугольником (Run and Debug) и нажимаем на
кнопку «Run and Debug». Сверху в
выпадающем списке следует выбрать «C++ (GDB/LLDB)» (это ранее
установленный компилятор gcc), затем, скомпилировать и выполнить
программу в режиме Debug (отладки):

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

Далее установим
еще одно расширение, которое будет отвечать за простой процесс запуска кода без
режима отладки. Чтобы можно было быстро и просто запустить программу и
посмотреть, что получается. Для этого переходим на вкладку «extensions» и набираем:

code runner

Это расширение
позволяет с помощью комбинации клавиш Ctrl+Alt+N компилировать и запускать
код. Результат отображается во вкладке «OUTPUT».

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

Последнее, что
нам осталось – это настроить компилятор на стандарт C99. Формально,
это делается с помощью специального флага -std следующим
образом:

gcc
-std=c99 -o outputfile sourcefile.c

Такой флаг нам
нужно добавить в настройках компилятора. Первым делом откроем файл tasks.json в
текущем каталоге и пропишем для ключа «args» первым
элементом этот ключ:

«args»: [

    «-std=c99»,

    …

    ]

Этот флаг будет
срабатывать при перекомпиляции проекта – комбинация клавиш Ctrl+Shift+B.

Точно такой же
ключ нужно добавить для компилятора, используемого расширением «Code Runner». Для этого переходим в меню File->Preferences->Settings и в строке набираем «code
runner run in terminal». Ставим
галочку.

Затем, в этом же
окне настроек набираем в строке «Run Code Configuration». Находим в настройках
раздел «Code-runner: Executor Map» и нажимаем на редактирование. Для ключа «c» после «gcc» прописываем «-std=c99» и ключ «code-runner.runInTerminal» устанавливаем в
false. Все, теперь
компилятор будет ориентироваться на стандарт c99 при
компиляции наших программ.

Видео по теме

Introduction

This is the guide to install the C & C++ Compiler on Windows. Here we are going to use the GCC Compiler ( not Turbo C++ which was used in the old stone age).

The reason why we are not using the Turbo C++ is becasue the development was discontinued. The last stable verion was on September 5, 2006. Eventhough there is an updated version available school and colleges are using the version 3 which was released in 1991.

You may argue that the Turbo C++ compiler is simple and easy to use and that’s not true. Of course it’s good to start with Turbo C++ but if you are planning to choose your career in programming Turbo C++ won’t help you on this. You have to go for the standard compilers used by the developer community.

This guide will helps you to install the latest C & C++ Compilers available in the industry, which is the MinGW GCC Compiler.

MinGW GCC Compiler

MinGW is a port of GCC to Windows. It was created to support the GCC compiler on Windows Platform. It lets us to access the headers and support libraries on Windows. It produces standalone Windows executables ( exe files ) which may be distributed in any manner.

Downloading

Go to mingw.org/ and click on the Download Installer button in the top right corner.

alt img

It will take you to sourceforge for downloading.

alt img

Installation

After the download, run the setup as Administrator

alt img

Click on Install

alt img

It is going to be installed in C:\MinGW\ folder.
Click on continue.

alt img

Then, it will fetch and update it’s database from the server, click on the continute button when it becomes clickable.

alt img

It will be on the Basic Setup Tab by default, there look for mingw-32-gcc-g++, Right Click and Mark for Installation

alt img

Now, Click on the Installation menu and hit Apply Changes.

alt img

It will open the confirmation dialog box, there click on Apply.

alt img

It will start downloading the required files.

alt img

Once the download gets completed it will install the packages, click on Close to finish the setup.

alt img

Checking the Installattion

In order to check whether it has installed correctly or not, you have to go to C:\MinGW\bin folder . There holding the shift key, right click on the empty area. Click on Open command window here

alt img

In the command prompt type the command gcc -v . It will show the version of GCC installed on your computer. If the output doesn’t look similar as this one then there will be some problem in your Installation.

alt img

Configuring

Setting the Environment Variable

The purpose of setting the Enviroment Variable is to access the gcc command everywhere in the command prompt. Setting up the enviromnent varaible will tell the system where to look for the gcc command.

Copy the C:\MinGW\bin path and click on This PC

alt img

Now right click on the empty area and click on Properties.

alt img

There choose Advanced system settings

alt img

It will open the System Properties dialog box, There click on the Enviroment Variables

alt img

In the System variables section look for Path and click on Edit

alt img

Append the Path C:\MinGW\bin in the Variable Value and click on OK

alt img

That’s all now you have successfully configured the GCC Compiler on
your Computer.

Usage

Here is the sample c program

#include <stdio.h>

int main(int argc, char const *argv[])
{
	printf("Hello GCC!\n");
	return 0;
}

Copy and paste this program on your Favorite code editor, save it as sample.c . If you are still using NotePad you have to read this guide Choosing the Best Code Editor.

alt img

Using from Command Prompt

Right Click on the Windows Icon (Start Menu Icon) and click on Command Prompt

alt img

Navigate the prompt to the place where you have saved the sample program ( use cd command to navigate ). Then type gcc sample.c to compile the program. Now a new executable named a will be generated in your folder. Type a on the command prompt to run the program.

alt img

That’s all this is how you have to compile and run C & C++ Programs on Windows.

  • Install bootcamp on windows 10
  • Input not supported при включении компьютера windows 10
  • Instagram com для windows 10
  • Install bluetooth driver for windows 10
  • Insta360 studio скачать для windows