Building gcc on windows

Building GCC on Windows

Instructions for a native bootstrap of GCC on Windows for i386-pc-mingw32.

These instructions will be merged into the GCC documentation when they become more mature.

Required Prerequisites

MinGW toolchain

You must have the MinGW toolchain installed to build GCC. The toolchain is composed of two parts, the host libraries and tools, and the host compiler. A complete toolchain which satisfies the requirements below can be installed using the installer from http://www.mingw.org.

These notes only discuss MinGW-specific prerequisite issues. Please see http://gcc.gnu.org/install/prerequisites.html for a complete list of prerequisites.

mingw-runtime (version 3.12 or higher): This is the equivalent of libc on Unix which provides an interface to Microsoft’s C runtime that is shipped with Windows.

Host Tools and Libraries

w32api: This is a free implementation of the Windows API, equivalent to the Windows SDK, which provides the system-level interface needed by mingw-runtime and some parts of GCC. It is possible, with some modifications, to use Microsoft’s Platform SDK instead.

binutils (version 2.15 or higher): The GCC build needs an assembler and linker.

gcc: You must have GCC 2.95 or better installed. At this time, building with other Windows compilers probably will not work.

Host Tools

Tools: A set of Unix-like tools must be present to build GCC. There are at least three different ways to get the set of required tools.

MSYS: MSYS is an environment available at that is designed to work with MinGW, and it should work seamlessly. MSYS is a stripped-down and specialized fork of Cygwin. Unfortunately, in the past, MSYS has suffered from various bugs that have made building GCC difficult.

Cygwin: The Cygwin environment available at http://www.cygwin.com can provide the host tools. An advantage of using Cygwin is that it comes with almost all of the tools needed for developing and testing GCC. If Cygwin is used, two modifications must be made:

  • ln that does not create Cygwin-style symbolic links must be placed in the path before Cygwin. The ln from MSYS should work here. This script can be used:
  • uname must be modified to report MINGW32_NT-5.1 instead of CYGWIN_NT-5.1 so config.guess guesses correctly. The easiest way is to just use the uname from MSYS. Alternately, you can pass —build=i386-pc-mingw32 to configure to override config.guess.

UnxUtils: UnxUtils from http://unxutils.sourceforge.net/ can provide the set of tools needed. Some manual adjustment will be necessary to get this to work correctly.

Optional Prerequisites

autogen: This is not included in Cygwin, MSYS, or UnxUtils. Presently, there is a problem with building autogen on Cygwin. For a workaround, see the autogen-users mailing list: http://sourceforge.net/mailarchive/message.php?msg_name=1ca1c1410805011500u33bfd13fk2eedcb98fd53435e%40mail.gmail.com.

mingw32-make: In some cases, the mingw32-make build provided on http://www.mingw.org may work better.

phreads-win32: This is needed presently to make libgomp compile. However, OpenMP does not actually seem to work at present on MinGW.

See http://gcc.gnu.org/install/prerequisites.html for a complete list of optional prerequisites.

Environment

All prerequisite tools should be in the PATH environment variable.

The console emulation in Cygwin and MSYS has a known problem that causes it to lose some output information from GCC, which can cause build failures to be rather mysterious. RXVT, for example, has this problem. For this reason, the Microsoft console should be used. Alternately, a console emulator that does not have this problem can be used, such as Console 2 from http://sourceforge.net/projects/console/.

Sometimes CRLF issues are a problem. Cygwin bash has a feature that can mitigate some of these problems, which can be activated in the following way: set -o igncr export SHELLOPTS

Читайте также:  Как установить обои для линукс

Including \r in the IFS environment variable may also be helpful in avoiding these problems.

Building

Please see the GCC installation instructions for complete details.

GCC must be configured using a relative path.

Building MinGW is typically quite slow, apparently due to slow Makefile and shell script execution. Using multiple processors with make -jN can substantially speed up the process.

To enable all languages and all directories (except mudflap), a command similar to the following example can be used. Note that you will need to specify your own paths to configure, libiconv, gmp, and mpfr.

../gccsrc/configure —enable-languages=c,ada,c++,fortran,java,objc,obj-c++ —disable-sjlj-exceptions —enable-libgcj —enable-libgomp —with-dwarf2 —disable-win32-registry —enable-libstdcxx-debug —enable-concept-checks —enable-version-specific-runtime-libs —prefix=/mingw —with-gmp=/mingw/src/gcc/gmp-mpfr-root —with-mpfr=/mingw/src/gcc/gmp-mpfr-root —with-libiconv-prefix=/mingw/src/gcc/libiconv-root

Installation

The DESTDIR variable can be used to control the output path.

make DESTDIR=/mingw/src/mytest/root install

None: WindowsBuilding (последним исправлял пользователь AaronLaFramboise 2008-06-03 20:12:58)

Как установить компилятор gcc / g++ для Windows. Установка gcc

15 декабря 2018

Время чтения: 5 минут

Для того, чтобы писать программы на 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 ещё не установлен в системе, поэтому двигаемся дальше.

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 и вы можете писать программы на языках 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.

Читайте также:  Драйвер ati mobility radeon hd 4650 series драйвера windows

Что ещё за 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 .

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

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

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

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

А Вы знаете, что мы пишем программы на C, C++, C#, Pascal и Python?

Так что если Вам нужно написать программу на C/C++, C#, Pascal или Python — мы с радостью поможем с этим!

В том числе мы занимаемся репетиторством по информатике и программированию, а также готовим к ОГЭ и ЕГЭ!

Почему именно мы?

  • Более 1800 выполненных заказов;
  • Более 170 отзывов;
  • Качественное решение
  • Короткие сроки и привлекательные цены
  • Различные акции и скидки

Как с нами связаться?

Programforyou — доверяя нам писать программы, вы получаете качественное решение в короткие сроки по привлекательной цене!

How to install the C language GCC compiler on Windows

On Linux, gcc is install by default and you can start to compile and execute C language code almost right away!

That’s not the case on Windows…

I have been struggling with how to do the same thing on Windows 10 for some time, but I finally succeeded

Here’s a video in which I explain the procedure:

Note: The procedure I describe here will not only allow you to install gcc, but also g++, gfortran, and many other useful tools that you usually only get in linux OS (like ls or grep)

1- What I want to teach you here

If you want a simple way to create programs based on C, C++, Fortran, etc… you will have to install a software with can compile the code you write into code that the machine understands

Such program is called a “compiler”

The most well know compiler for C language is the GNU compiler called GCC.

There are actually several compilers which go together like a suite:

  • for C++, you have the compiler g++
  • for Fortran, the compiler is called gfortran

Why using the gcc compiler?

If you are on Windows, you probably heard about software such as visual studio from Microsoft which also you to write and compile C and C++ code as well.

That’s true, and it’s totally fine if you want to use it…

I am personally not such a big fan of Visual Studio because of the following reasons:

  • It is huge to download and install (between 10 and 20 GB if I remember)
  • It’s a big pain to set up the first time
  • Building even a very simple project takes much more time than it should

Because of that, I find that I kind of takes out the fun of programming and seeing immediately the result of what you did…

Now, for large pieces of software, visual studio is probably the way to go

2- How to use the gcc compiler?

Once installed on your machine, gcc is just a piece of cake to use to compile a simple c language code

Step 1: Write your c code

For example, let’s take this Hello World example

Читайте также:  Установка второй операционной системы когда уже есть linux

Step 2: Compile using gcc

Write the following line of code into your terminal:

This will generate an executable binary file called helloworld.exe which can be used to run your code

Step 3: Execute your code

Just go into the directory where your executable is and run it by writing “helloworld.exe”

2- The principle

Now that you understand how it can be easy to start with writing C code, let’s talk about the difficult part…

How to actually install gcc on Windows…

The reason it is easy to install compilers and other kind of open source software on linux is because you have a very powerful command line terminal called bash which handles the installation, uninstallation and upgrade of software using a software called “apt” on debian-based linux systems.

On Windows, if you want to have gcc (and the other compilers too), you have to download the source code and find a way to compile it…

For that, you will need to install first other software called pre-requisites which will also need to be compiled, etc…

You can spend several days trying to do that if you are really motivated

I will present you another way much simplier!

For that I will have to install a software called MSYS2, which is an “easy” way to give some linux feel to your Windows PC and able it to install programs almost as easily as in linux…

You will be able to install gcc just with one command line like this:

3- Installing MSYS2 on your PC

What is MSYS2?
According to their website, MSYS2 is a software distribution and building platform for Windows

The Website: https://www.msys2.org/

Installing it is actually a peace of cake

Just download the correct installer and launch it with admin rights and you are good to go

Expected something more complex?

Sorry about that

Once you installed it, you will see 3 programs appear in your list of programs:

  • MSYS2 MinGW 32-bit
  • MSYS2 MinGW 64-bit
  • MSYS2 MSYS

Run the 3rd one MSYS2 MSYS to open a special command window in which you can input commands and start to install programs

The package management system which is equivalent to apt-get on linux is called pacman

When you install MSYS2 for the first time, you have to update pacman using the following command:

4- Installing GCC and other development tools with the pacman package management system

Then you can start to install gcc and other developer tools using pacman like this:

This command will install first a set of development software included in a package called base-devel and then it will install gcc, vim and cmake

vim is optional, but always good to have 😉
(You can also install emacs very easily in the same way)

In the package base-devel, you have 53 useful developement tools that can be installed:

5- Last Important Step: Add Executables to your Windows PATH

Now you are able to install all those packages easily, but how to access them through the normal windows command line?

For that, you have to add the two following directories to your PATH:

To add anything to your PATH in Windows 10:

1- Search “Advanced System Settings” in the search bar

2- Open the “environment variables” window, click on the PATH variable and click on “Edit”

3- Click on the “New” button and add the 2 following directories to your PATH

Important Note: This adds a lot of executables to your path which might conflict with other applications. The usr\bin\ directory contains the whole slew of executables listed above. There is a lot of unnecessary stuff in that directory.

4- Click on OK on all the windows and open a new Command Window and you will be able to use gcc into your windows command prompt!

That’s all for today, hope you understand better now how to install and use GCC and other linux tools on windows!

I will write new articles soon about how to develop simple programs in C.

Let me know through the comments if there is something special that you want to understand!

PS: If you like what I write, subscribe to the newsletter and help me to spread the knowledge by sharing this article! We all win by learning from each other and making the engineering knowledge more accessible 🙂 THANK YOU!

Оцените статью