Gcc on windows cygwin

Cygwin: Введение

Эта статья будет полезна начинающим пользователям Cygwin. Начнем с того, что нам для начала нужно ответить на простой вопрос. Что же такое Cygwin? Cygwin — это UNIX-подобная среда и интерфейс командной строки для Microsoft Windows. В системе Microsoft Windows уже существует подобный интерфейс cmd. Вызвать командную строку можно сочетанием клавиш Win+R. Но зачастую большую часть работы Windows пользователям приходится делать вручную. По другую сторону Linux пользователь уже давно написал bash-скрипт и сидит пьет пиво в сторонке от автоматизированного рабочего процесса.

Так что же мешает сделать это и в ОС Windows? Правильно, абсолютно ничего не мешает. Но для этого нужны дополнительные программы и библиотеки. Программа Cygwin расширяет возможности стандартной командной строки Windows, позволяя автоматизировать некоторые процессы и разрабатывать программы для Linux и других систем.

Выбираем нужную версию, скачиваем и запускаем исполнительный файл setup-x86.exe и setup-x86_64.exe соответственно.


Окно установки 64 битной версии программы


Окно выбор способа установки


Окно выбора пакетов

Окно установки 32 битной версии программы выглядит точно так же как и 64 битной. Следующим шагом будет окно выбора. Откуда устанавливать или скачивать программу. Всего есть три варианта. Первый вариант Install from Internet (downloaded files will be kept for future re-use) установка из интернета причем загруженные файлы будут храниться до следующего повторного использования. Второй вариант Download Without Installing скачать без установки. Третий вариант Install from Local Directory установка из локального каталога. Т.к. у нас нет локальной копии и нам нужно установить то выбираем первый вариант. Следующее окно будет выбор пути установки. Рекомендую выбрать системный диск, к примеру у меня путь установки Cygwin это C:\cygwin64. Следующее окно это выбор пути где будут храниться временный файлы которые будут скачиваться в процессе установки. У меня это C:\cygwin64\package. Потом нужно выбрать как скачивать через прокси или напрямую. Следующим шагом будет выбор репозитория скачки выбираем любой попавшийся или тот что по умолчанию и жмем Далее. После нажатия кнопки далее начнется процесс скачивания основных конфигов. Следом вы сможете выбрать что устанавливать. Чтобы выбрать пакет нужно нажать Skip около названия пакета. Список пакетов которые вам пригодятся:

  • gcc-core (в разделе Devel)
  • gcc-g++ (в разделе Devel)
  • make (в разделе Devel)
  • cmake (в разделе Devel)
  • automake (в разделе Devel)
  • wget (в разделе Web)
  • libiconv (в разделах Devel и Libs)
  • openssh (в разделе Net)
  • nano (в разделе Editors)
  • bash (из раздела Base)
  • base-cygwin (из раздела Base)
  • base-files (из раздела Base)
  • cygwin (из раздела Base)
  • file (из раздела Base)
  • gzip (из раздела Base)
  • login (из раздела Base)
  • mintty (из раздела Base)
  • openssl (из раздела Base)
  • run (из раздела Base)
  • tar (из раздела Base)
  • vim-minimal (из раздела Base)
  • cron (из раздела Admin)
  • shutdown (из раздела Admin)
  • git (все пакеты из раздела Devel)

Также рекомендую полностью установить раздел Perl и Python. После этого жмем далее и произойдет установка нужных пакетов и их зависимостей. После конца установки можно будет запустить сам Cygwin и начать работу.

Мне не симпатизировал ни цвет фона, ни встроенный шрифт и цвет текста поэтому я кастомизировал его. На этих словах я закончу эту статью.

Данная статья не подлежит комментированию, поскольку её автор ещё не является полноправным участником сообщества. Вы сможете связаться с автором только после того, как он получит приглашение от кого-либо из участников сообщества. До этого момента его username будет скрыт псевдонимом.

Preshing on Programming

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.

  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, build and install it.
  4. Test the new GCC compiler in C++14 mode using the -std=c++14 option.

[Update: As a commenter points out, 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.

Читайте также:  Geforce 210 mac os catalina

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:

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.

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.

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.

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.

Читайте также:  Создание загрузочной флешки под uefi linux

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:

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

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

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:

Check out Plywood, a cross-platform, open source C++ framework:

Recent Posts

Copyright © 2021 Jeff Preshing — Powered by Octopress

GCC on Windows — Bash on Ubuntu on Windows (WSL), CygWin, MinGW

I’m currently using windows 8.1 and was looking to install GCC. I found out that the ways to do this is through MinGW and CygWin (the most popular). Now I came up on the Windows Subsystem for Linux (WSL)and Bash offered on Windows in Windows 10.

Question 1. whether it is possible to have GCC installed through the Bash in Windows 10, and will it work as it does on a Linux distribution. Say you have a ‘helloworld.c’ file, and if I do,

in the bash would i get the output (assume the contents of ‘helloworld.c’ to be simple — a cout statment.)

Question 2. If it is possible then, which of the methods is preferred to use GCC on Windows. That is, a)MinGW or CygWin b)Bash on Linux on Windows. Because based on what I understood on what I read, CygWin and MinGW causes some dependencies on programs developed on them.

Question 3. If you have read this far then please fill in my gap in understanding about CygWin and MinGW. That is if I use it only for compiling and running pieces of code and not application developement, it doesnt matter which of these I use, am I right? Because the code (written in C or FORTRAN), will compile and execute the same irrespective of the system, am I right?

Читайте также:  Hp smart windows 10 exe

Context. I am a student working on numerical computations (Computational Fluid Dynamics) and my main work is to develop and run CFD codes in FORTRAN. What I want to do is work on the computational code (for which we use FORTRAN mainly) on my laptop which runs on Windows. And I am not looking to develop applications or softwares for either Windows or Linux at the moment. But I’d still like to know how things work and which is the best option. Please explain in detail. Thank you.

1 Answer 1

To answer your first question, yes, you can do that compile under WSL.

To answer your other questions, let’s look at MinGW. This is what the Wikipedia entry for MinGW says:

MinGW was forked from version 1.3.3 of Cygwin.[5] Although both Cygwin and MinGW can be used to port Unix software to Windows, they have different approaches:[16] Cygwin aims to provide a complete POSIX layer comprising a full implementation of all major Unix system calls and libraries. Compatibility is considered higher priority than performance. On the other hand, MinGW’s priorities are simplicity and performance. As such, it does not provide certain POSIX APIs which cannot easily be implemented using the Windows API, such as fork(), mmap() and ioctl().[16] Applications written using a cross-platform library that has itself been ported to MinGW, such as SDL, wxWidgets, Qt, or GTK+, will usually compile as easily in MinGW as they would in Cygwin.

Windows programs written with Cygwin run on top of a copylefted compatibility DLL that must be distributed with the program, along with the program’s source code. MinGW does not require a compatibility layer, since MinGW-based programs are compiled with direct calls to Windows APIs.

This is what the MinGW web page (http://www.mingw.org) says:

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

MinGW provides a complete Open Source programming tool set which is suitable for the development of native MS-Windows applications, and which do not depend on any 3rd-party C-Runtime DLLs. (It does depend on a number of DLLs provided by Microsoft themselves, as components of the operating system; most notable among these is MSVCRT.DLL, the Microsoft C runtime library. Additionally, threaded applications must ship with a freely distributable thread support DLL, provided as part of MinGW itself).

MinGW compilers provide access to the functionality of the Microsoft C runtime and some language-specific runtimes. MinGW, being Minimalist, does not, and never will, attempt to provide a POSIX runtime environment for POSIX application deployment on MS-Windows. If you want POSIX application deployment on this platform, please consider Cygwin instead.

I am familiar with WSL and Cygwin more than MinGW. From what I know, MinGW is more targeted to producing reasonably portable, high-performance Windows binaries whereas Cygwin is more targeted to Unix users (or those wanting to port applications that were written for Unix/POSIX) who want a Unix-like environment under Windows with all the trimmings. As you indicated, Cygwin programs at least used to be less easily distributable to others who don’t have Cygwin installed (due to license considerations, but see the link below). MinGW programs run as native Windows programs using undocumented Windows native libraries. WSL binaries don’t run under Windows by themselves; they only run in the WSL environment (or possibly native Linux systems). WSL maps Linux kernel calls to Windows kernel calls, whereas Cygwin implements Unix/Posix library calls. WSL relies on a real Linux distribution to provide it’s environment, whereas Cygwin relies on its own environment. (WSL has an advantage in that it will run existing binaries without recompilation.) I don’t think any of this is too important to you, because you’re not planning on distributing your binaries. You want high performance. According to Wikipedia, MinGW is higher performance than Cygwin, but it’s also 32-bit which may be a problem with your applications. There is a 64-bit environment similar to MinGW but it’s a different project.

An important consideration is whether you want to write Windows code or Unix/Linux/POSIX code. MinGW is for developing Windows applications using Windows APIs (although you can fold in some limited POSIX support); WSL and Cygwin are for developing Unix/Linux/POSIX applications. This matters for portability purposes. But if you are developing the type of programs I think you are, nearly all straight computations and very little fancy I/O, it may just boil down to personal preference or convenience. If you can come up with a small representative program that takes a significant amount of time and try running it under each environment, you can find out which has the best performance. That is going to depend I think on your own mix of operations.

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