Что такое mingw linux

MinGW

MinGW — это программный набор инструментов для создания дополнений, ранее известный как mingw32. С помощью ПО можно разрабатывать приложения под Виндовс. Программа состоит из компилятора порта ССС (GNUCompilerCollection) и набора библиотек под свободной лицензией для Виндовс API. На этой странице можно скачать последнюю версию МinGW.

Лицензия Бесплатная
ОС Windows 7 и выше
Язык интерфейса Русский, английский
Разработка Colin Peters
Разновидность программы Для компиляции

Обзор программы

Команда проекта предоставляет пользователям следующие компоненты:

  • доппакеты — порты GNUtoolchain, которые управляются из командной строки Виндовс или интегрируются в IDE;
  • MSYS (MinimalSYStem) — порты win32, представляющие собой лёгкую оболочку Unix с rxvt и инструментами POSIX для работы со скриптами autoconf;
  • заголовочные файлы Win32 и одноименные для библиотек импорта.

Для установки ПО первым шагом надо бесплатно скачать МinGW на ПК, выбрав путь без пробелов. Рекомендуется назначить корень диска, например С:\ХХХ\MinGW. Ярлык в пусковом меню создавайте по желанию или отмените операцию, выставив галочку рядом с Don’tcreate a StartMenu folder.

Вам понадобятся пакеты:

  • MSYS BasicSystem;
  • C Compiler;
  • MinGW DeveloperToolKit;
  • C++Compiler.

После подтверждения установки появится окно с отображением прогресса скачивания. Нужно следить, чтобы не было ошибок — при недоступности тех или иных ресурсов установку придётся повторить позже.

Теперь добавьте путь до директории C:\ХХХ\MinGW\bin в переменную PATH:

  • кликните правой клавишей мышки ярлык Компьютер;
  • нажмите «Свойства»;
  • далее «Доппараметры системы» и «Переменные среды»;
  • найдите Path, дважды нажмите, чтобы вызвать окно редактирования.

Добавьте путь до директории \bin, в нашем условном случае это будет C:\ХХХ\MinGW\bin с разделением путей через «;». На этом этапе завершается установка MinGW и оболочки. Для дополнительных пакетов рекомендуется назначить ярлычки.

Используйте набор команд mingw-get install+msys-man/msys-wget/msys-zip/msys-unzip/msys-bzip2/msys-perl, где базовая команда mingw-get install относится к аналогу вида apt-get install под дистрибутивы Linux.

Перечень других дополнительных пакетов вызывается mingw-get show, удаление ненужного пакета mingw-get remove+удаляемые файлы. Для удобной работы рекомендуются утилиты консольного редактора vim или более привычного многим юзерам Notepad++. Архивацию и распаковку проводите с 7-zip.

Подробную инструкцию вы можете получить из справочного раздела о программе или посетив официальный сайт МinGW.

Источник

MinGW

MinGW — Minimalist GNU for Windows

Colin Peters, Jan-Jaap van der Heijden, Mumit Khan, Anders Norlander, Earnie Boyd, Dale Handerson и др.

MinGW (англ. Minimalist GNU for Windows ), ранее mingw32, — нативный программный порт GNU Compiler Collection (GCC) под Microsoft Windows, вместе с набором свободно распространяемых библиотек импорта и заголовочных файлов для Windows API. MinGW позволяет разработчикам создавать нативные приложения Microsoft Windows [1] . В MinGW включены расширения для библиотеки времени выполнения Microsoft Visual C++ для поддержки функциональности C99 [1] .

Содержание

История

MinGW изначально назывался mingw32; цифры были отброшены, чтобы преодолеть заблуждение, что MinGW ограничен 32-битными системами [2] . Первый релиз, созданный Колином Петерсом (англ. Colin Peters ) в 1998 году, включал в себя только порт GCC из Cygwin [3] [4] . Нативный Windows-порт GCC, созданный Jan-Jaap van der Heijden и добавленные binutils и make [3] [4] . Mumit Khan позже принял участие в разработке, добавив в комплект больше специфичных для Windows возможностей, включая заголовочные файлы Win32, написанные Anders Norlander [3] [4] . В 2000 проект был перемещён на SourceForge.net, чтобы получить большую поддержку общественности и централизовать разработку [3] [4] .

В сентябре 2005 MinGW был выбран проектом месяца на SourceForge.net [4] .

Компоненты MinGW

Проект MinGW поддерживает и распространяет несколько различных ключевых компонентов и дополнительных пакетов, включая различные порты GNU toolchain, такие как GCC и binutils, переведённые в эквивалентые пакеты [5] [2] . Эти утилиты могут быть использованы из командной строки Windows или интегрированы в IDE.

В дополнение, компонент MinGW, известный как MSYS (Minimal SYStem) предоставляет win32-порты окружения легковесной Unix-подобной оболочки, включающей rxvt и набор инструментов POSIX, достаточный для запуска скриптов autoconf [6] .

Реализации заголовочных файлов Win32 и библиотек импорта Win32 для связывания во время выполнения программы от начала до её завершения имеют либеральную лицензию [7] , а порты GNU доступны под GNU General Public License. Бинарные сборки полного пакета MSYS и отдельных MinGW GNU утилит доступны для скачивания на сайте MinGW.

Сравнение с Cygwin

MinGW отделился от Cygwin 1.3.3. Несмотря на то, что и Cygwin, и MinGW используются для портирования программного обеспечения Unix под Windows, они используют разный подход [8] : цель Cygwin — предоставить полный слой POSIX (подобный тому, который находится в Linux и других Unix-системах) над Windows, жертвуя производительностью там, где это необходимо для совместимости. Соответственно, такой подход требует от Win32 программ, написанных с Cygwin, запуска поверх копилефтной библиотеки совместимости, которая должна распространяться с программой, а также с исходным кодом программы. Целью MinGW является предоставление нативной функциональности и производительности посредством прямых вызовов Windows API. В отличие от Cygwin, MinGW не нуждается в DLL-слое совместимости и, таким образом, программы не обязаны распространяться с исходным кодом.

Вследствие того, что MinGW использует вызовы Win32 API, он не может предоставить полного POSIX API; он не может скомпилировать некоторые приложения Unix, которые могут быть скомпилированы с Cygwin. В частности, это относится к приложениям, которые требуют такой функциональности POSIX, как fork(), mmap() или ioctl() [8] и предполагают запуск в среде POSIX. Приложения, написанные с использованием кроссплатформенных библиотек, таких, как SDL, wxWidgets, Qt или GTK+, как правило, легче компилируются в MinGW, чем в Cygwin.

Комбинация MinGW и MSYS предоставляет небольшую независимую среду, которая может быть загружена на съемные носители, не требуя добавления записей в файлы реестра. Cygwin, предоставляя бо́льшую функциональность, является более сложным для установки и поддержки.

Также возможна кросс-компиляция приложений Windows с MinGW-GCC под управлением операционных систем семейства POSIX. Это означает, что разработчику не нужно устанавливать Windows с MSYS, чтобы скомпилировать программы, которые будут запускаться под Windows без Cygwin.

Источник

Cygwin или MinGW? Собираем программы для Windows без Windows

Содержание статьи

В общем-то, даже в Microsoft уже признали проблему и сделали WSL (Windows Subsystem for Linux), чтобы запускать те приложения, у которых нативных версий под Windows нет. Однако если ты хочешь сделать свою программу доступной для широкой аудитории, то WSL вовсе не панацея, поскольку у среднего пользователя эта система вряд ли установлена и у нативных приложений возможностей для интеграции с Windows все равно больше.

Во многих случаях камень преткновения — не сам код программы, а система сборки. Если ты используешь кросс-платформенные библиотеки и не вызываешь специфичные функции POSIX, портирование может вообще не требоваться. Главное — собрать исполняемые файлы.

Сборка-то обычно и зависит от окружения POSIX. Если ты используешь GNU autotools, то скрипт ./configure у тебя на Bourne shell. CMake и ряд других систем сборки умеют генерировать скрипты под целевую ОС, но остается последняя «маленькая» проблема — нужна проприетарная и не бесплатная ОС. Есть вариант переложить задачу ее развертывания и лицензирования на кого-то другого и обратиться к сервису вроде Appveyor. Но можно вместо этого воспользоваться способностью GCC к кросс-компиляции и собирать программы на хосте с Linux (или macOS).

GNU и Windows

Для сборки программ с помощью GNU toolchain на Windows часто используют два проекта: Cygwin и MinGW + MSYS. У них схожие цели, но разные детали реализации. Давай разбираться.

Cygwin

Cygwin — самая полная реализация окружения GNU для Windows. Он предоставляет большую часть POSIX API в виде библиотеки, что позволяет собирать программы из UNIX без портирования, если только им не требуется семантика UNIX. Яркий пример — демоны, им нужен fork() и сигналы, которых нет в Windows, да и службы Windows устроены совсем иначе.

Кроме библиотеки, дистрибутив содержит набор классических команд UNIX и терминал. Реализации команд используют эту библиотеку и поддерживают некоторые возможности UNIX, такие как регистрозависимые имена файлов.

Целевой способ использования: если нет желания или возможности портировать программу на Windows или использовать только платформенно независимые API, ее можно собрать «под Cygwin», ценой зависимости от cygwin1.dll и относительной изоляции от всей остальной системы.

Многие люди ставили и продолжают ставить окружение Cygwin, чтобы иметь возможность использовать классические команды UNIX на Windows. Некоторые разработчики также включают Cygwin в инструкции для сборки своих программ под Windows, хотя сама программа не связывается с cygwin1.dll . Для этой цели может быть более правильно использовать MSYS.

MinGW и MSYS

Если цель Cygwin — сделать возможной сборку немодифицированных приложений на Windows ценой внешней зависимости, то цель MinGW + MSYS — производить приложения без внешних зависимостей.

MinGW и MSYS — это независимые пакеты, но их часто путают и смешивают друг с другом (а часто путают и с Cygwin). Можно сказать, что MinGW — это эквивалент GCC и binutils, а MSYS — расширенный эквивалент coreutils.

Начнем с MSYS. MSYS — это более «нативная» и легковесная альтернатива Cygwin. Этот пакет включает библиотеку с реализациями функций POSIX, но она предназначена для внутреннего пользования, и авторы категорически не рекомендуют связывать с ней свои приложения.

Библиотека MSYS не реализует UNIX поверх Windows, а следует соглашениям Windows — к примеру, сознательно не учитывает регистр букв в путях к файлам. Главная цель MSYS — предоставить нужные для скриптов сборки программы вроде Bourne shell, make и прочее, что обычно требуется для autotools.

MinGW содержит версии GCC и binutils (ассемблер as, компоновщик ld и так далее), которые производят исполняемые файлы для Windows в формате PE/COFF. Здесь мы и подходим к ключевому моменту: MinGW, как и все остальные части GNU toolchain, такой же платформенно независимый проект.

Кросс-компиляция в GNU toolchain уже давно обычное дело, и в GCC целевая платформа и хост независимы друг от друга. Можно запускать GCC на Linux для x86 и собирать программы для Linux на ARM, или наоборот. Совпадать не обязаны не только рабочая и целевая архитектуры процессора. Точно так же не обязаны совпадать даже ОС и формат исполняемого файла.

Ставим MinGW

Авторы многих дистрибутивов GNU/Linux уже постарались за нас, так что многие кросс-версии GCC, включая MinGW, можно поставить из репозиториев.

Например, в Fedora:

Если ты используешь macOS, то MinGW можно поставить из Homebrew: brew install mingw-w64 .

MinGW-w64, несмотря на название, поддерживает и Win32, и Win64. Это форк MinGW, который создали в первую очередь для реализации недостающей в оригинальном проекте поддержки Win64, отсюда и название.

В Fedora также присутствует ряд готовых кросс-версий популярных библиотек, например mingw32-qt .

Hello World

Для демонстрации соберем традиционный hello world. У кросс-версий GCC всегда есть префикс, для MinGW используются префиксы i686-w64-mingw32 и x86_64-w64-mingw32 .

Тестирование кросс-компилированных программ для других архитектур — непростая задача, но, поскольку наша целевая платформа — Windows на x86, мы легко можем протестировать их в Wine:

Продолжение доступно только участникам

Вариант 1. Присоединись к сообществу «Xakep.ru», чтобы читать все материалы на сайте

Членство в сообществе в течение указанного срока откроет тебе доступ ко ВСЕМ материалам «Хакера», позволит скачивать выпуски в PDF, отключит рекламу на сайте и увеличит личную накопительную скидку! Подробнее

Источник

Mingw

MinGW (historically, MinGW32) is a toolchain used to cross-compile Windows binaries on Linux or any other OS. It can also be used natively on Windows to avoid using Visual Studio, etc. MinGW-w64 is a fork of MinGW with support for 64-bit Windows executables. This article uses the MinGW-w64 runtime for both 32 and 64 bit target support.

Contents

Installation

Prerequisites

To install the MinGW Toolchain, start with emerging the crossdev tool:

We use a target descriptor to tell crossdev , what to build: $outputarch-$runtime-mingw32 .

Throughout this article, the 32-bit toolchain has $outputarch == i686 , the 64-bit toolchain has $outputarch == x86_64 . As we only use MinGW-w64 as runtime, $runtime == w64 . Don’t be confused by mingw32 , this is just a legacy name.

Quickstart

After crossdev is installed, the most basic command of interest will install the MinGW cross-toolchain for 64 bit:

To install the toolchain for 32 bit (which also uses MinGW-w64 runtime), use:

You may either use the cross compiler directly, or use the cross-emerge wrapper symlink.

The resulting .exe can be found here:

You may also wish to configure the cross-portage environment found in:

Emerge

Preparation

Crossdev will automatically create /etc/portage/package.keywords/cross-x86_64-w64-mingw32 and /etc/portage/package.use/cross-x86_64-w64-mingw32 (or their 32-bit counterparts). Since by default some critical use flags like sanitize , fortran or vtv are not disabled it might be necessary to override the auto created use flags by

If not set already set add crossdev-overlay to repos.conf:

Now with the crossdev tool installed, emerge the MinGW toolchain.

Toolchain installation

To build the 64-bit windows toolchain:

To build the 32-bit windows toolchain:

Adding the —ex-insight or —ex-gcc options may cause issues; they have been known to not build. —ex-gdb will enable GDB and likely will work, but it is not very useful on Linux because MinGW GCC by default makes PE’s (EXE files), not ELF files, and gdb has no idea how to run an EXE file on Linux. A remote debugger (with a Windows target machine) is a possibility but a long shot.

Notes

  • GCJ sources will not compile due to missing makespec files that do not get installed (copying from MinGW from Windows does not work either).
  • Sanitize may cause compilation failures for at least gcc-4.9, maybe newer.
  • OpenMP was once forcefully disabled in the ebuild, but now honors the use flag setting. However it may still cause compilation issues when set.

Compiling other parts of the runtime

MinGW-w64-runtime supplies some development tools and libraries, in particular a pthreads implementation which has features the one below does not. Before you take this step, make sure to backup the contents of /etc/portage/package.use/cross-x86_64-w64-mingw32 as this next step will overwrite it with a new line for the runtime. If you don’t edit this file to add in the old contents back into this file, when you do a update looking for changes in use flags, emerge will try to re-emerge the compilers with the multilib flag on.

libssp

The GCC USE flag sys-devel/gcc[libssp] has been masked, since it is usually provided by libc. Apparently msvcrt does not provide libssp, so it is recommended to re-enable this USE flag for cross compilation (see package.use.mask):

Usage

Portage

The cross environment is a totally independent portage instance, which is configured in /usr/x86_64-w64-mingw32/etc/portage .

When building packages, it might just work. Most things do not. Try with USE=»-*» after a failed build, then selectively add USE flags you need. If that does not work, then you probably cannot use Portage to install the package desired for use with MinGW. Of course, as with any bug, you may hunt it down and make the world a better place.

Settings

You may want to adjust some cross-portage defaults like the temporary build directory:

Profile settings

Various ebuilds support mingw or win32 targets, but different build systems often need different indicators. Ensuring the following are set in /usr/x86_64-w64-mingw32/etc/portage/profile/make.defaults should allow most build systems to detect the proper target. Note, some of these may have already been set by crossdev :

make.conf tweaks

Mingw64-runtime and the cross-toolchain do not provide any libgcc_s_*.dll files, and without an external source for these files (eww) there will be issues trying to execute what is built by the cross-toolchain. Fortunately, there’s a workaround in the form of LDFLAGS -static-libgcc and -static-libstdc++ , however due to the fact that these non-standard flags tend to get stripped out of builds, you need to perform some trickery. Add the following to the make.conf :

USE flags can be set globally in make.conf or per-package in package.use ; as the builds are for win32 it likely makes sense to globally disable some flags, such as USE=»-X» and globally enable USE=»win32″ in case any packages support it.

Finally, you likely want to make sure that the code you compile will actually run on the targets you plan to execute it on. This means setting appropriate -march and -mtune values in the CFLAGS variable for the target platform:

Emerging packages

Cross emerging is done by x86_64-w64-mingw32-emerge . For example, to emerge the sys-libs/zlib package, use:

Alternatively you can deleting the content of /usr/x86_64-w64-mingw32/var/lib/gentoo/news/news-gentoo

Using Portage, you may run into problems such as the following:

  • Application wants GDBM (see below).
  • Application wants to link with ALSA/OSS/Mesa/other library only useful to X or Linux.
  • Ebuild of application doesn’t contain the necessary configuration option to support a mingw or win32 target.
  • Application is an unnecessary utility script, such as gentoo-functions or eselect .
  • An ebuild inherits multilib and specifies MULTILIB_CHOST_TOOLS without adding $(get_exeext) .

In the multilib case, emerge wants to move the executables specified in MULTILIB_CHOST_TOOLS . But when cross compiling with mingw32 the executables receive an extension .exe and emerge cannot find the file without extension and fails. If you encounter this sort of error, please post to the bug #588330 mentioning your package. In the meantime you may fix it by overlaying (see below) a custom ebuild, appending the extension $(get_exeext) to all files in MULTILIB_CHOST_TOOLS .

The main techniques to tweak ebuilds to make them work are

Overriding use flags, keywords and configuration options

To override use flags and keywords, simply use /etc/portage/package.use/ and /etc/portage/package.keywords/ respectively. For the configuration options, we can tell emerge to use a package specific file defining environment variables (see package.env). For example, if we want to configure x11-libs/cairo with —with-target=win32 , we create

User patching

Most ebuilds call epatch_user , searching for user patches in $/etc/portage/patches/ . See /etc/portage/patches for more details how to use user patches.

This means you can place patches in /usr/x86_64-w64-mingw32/etc/portage/patches/$category/$package to apply them only for cross-building.

Overlaying

If issues cannot simply be fixed by overriding configure options, in some cases we have to override ebuilds. In order to do that we create a custom ebuild repository which is only active for the cross environment! Since /usr/x86_64-w64-mingw32/usr/portage is empty, we will use this path.

Create the following files:

Portage will then use our custom ebuilds in the /usr/x86_64-w64-mingw32/usr/portage/ folder when we’re building for Windows.

Notes on specific packages

app-admin/eselect

This package brings in a number of system dependencies that are just plain not needed to build win32 software, and at the time of writing many of them (like python) fail to emerge. However, as the binary is called during phase functions of other ebuilds you do want, a simple package.provided entry does not suffice to get rid of it. Instead, I recommend overlaying your own app-admin/eselect ebuild that installs a dummy eselect binary, something that will do nothing yet always return success. This is a dirty hack that certainly has drawbacks, but it at least allows the meat of slotted packages to be emerged.

The ebuild could look for example like this

sys-apps/gentoo-functions

This is another one of those necessary tool dependencies that isn’t really needed in a mingw cross-build environment. Although mostly implemented in shell, there is a single compiled binary that fails due to missing POSIX API stuff, /sbin/consoletype . This package may be something that can be package.provided away, but to be on the safe side one can also overlay this ebuild and install a dummy script that echo’s ‘serial’ and exists with code 1, in place of compiling consoletype.

dev-util/gtk-update-icon-cache

gtk-update-icon-cache is a tool that various packages inheriting the gnome eclasses will call in their pkg_postinst phase functions. Although it may be a good idea to install it for use within the win32 target environment, the resulting binary cannot be run in phase functions and so failures will often occur. Another dummy-script-installing overlay package can get around this issue.

OpenSSL

Follow this guide: [1]

sys-libs/ncurses

Ncurses is a very finicky package, mostly due to the fact that it’s build system was generated using a custom-forked version of autotools. At this time of writing, sys-libs/ncurses-5.9-r5 is stable and a static-only installation will emerge with EXTRA_ECONF=»—enable-term-driver —enable-sp-funcs —without-shared» and USE=»static-libs» , but ncurses-6.0 will not compile.

sys-libs/readline

sys-libs/readline is another finicky package, in part because it depends on ncurses. Only

sys-libs/readline-6.2_p5 will build successfully, newer versions need a lot of patching. Further, due to ncurses being limited to a static-only installation, readline must also be built static-only using EXTRA_ECONF=»—disable-shared» and USE=»static-libs» .

x11-libs/cairo

Cairo is well supported but the ebuilds currently do not provide a USE flag for the win32 target. Specifying EXTRA_ECONF=»—with-target=win32″ and ensuring USE=»-X -aqua -xcb -x11-xcb» will address this for now.

If the plan is to emerge x11-libs/gtk+, then we abuse the aqua use flag (both packages do not provide a win32 use flag) in order to avoid forced X11 dependencies ans set USE=»aqua» for both packages. This will enable quartz support via configure options which we have to suppress by specifying EXTRA_ECONF=»—enable-quartz=no —enable-quartz-image=no» .

x11-libs/gdk-pixbuf

This package builds as-is without any modification, however there are two minor issues related to using the package:

  • The pkg_postinst phase is unable to run ‘gdk-pixbuf-query-loaders’ to generate the loaders.cache file, which means that this will need to be done by hand using wine, via something like
  • The paths used by gdk-pixbuf at runtime to find the various loader DLLs is absolute, meaning that they will need to be installed on target win32 systems at [drive]:\usr\lib\gdk-pixbuf-2.0\2.10.0\loaders .

is possible to circumvent both of these issues by building the gdk-pixbuf with EXTRA_ECONF=»—with-included-loaders=yes» , as this will include the loader code directly in the main gdk-pixbuf dll.

x11-libs/gtk+

As touched on in the section about cairo above, in order to avoid a lot of X11 deps, gtk+ needs to be built with USE=»aqua» and EXTRA_ECONF=»—with-gdktarget=win32″ for gtk+:2 or EXTRA_ECONF=»—enable-win32-backend —disable-quartz-backend» for gtk+:3.

If build failures related to missing symbols are seen in the libraries at installation time, this may be related to a need to clear the gtk.def file so that it can be regenerated properly by the build system. An easy way to do this without overlaying the ebuilds is to use the following script snippet in /usr/i686-w64-mingw32/etc/portage/bashrc :

These are «Standard GNU database libraries» according to Portage. Many libraries and applications depend on this. The package reportedly compiled successfully compiled in the past, but the current versions in Portage do not compile due to the package requiring a POSIX environment (which mingw is not). Patching is very much needed.

To get around this problem for the moment, try building with USE=»-*» .

SDL tutorial example

Try compiling this source code (save to test.c ).

Use the following command to build:

Test with Wine (requires SDL.dll to be somewhere in Wine’s %PATH% , which includes the same directory as the EXE):

If you get a window named SDL_app, then it worked. The window will automatically exit after about 5 seconds (the Windows Sleep() function halts execution for 5000 milliseconds).

Hello World Example

Simple Win32 C program to test installation and function. [3]

To build GUI, -mwindows is added (default is -mconsole )

Verify with file.

POSIX threads for Windows

At least two alternatives exist to port applications with POSIX threads to windows. One option is to use a wrapper library that provides a POSIX-compatible API on top of the win32 thread functions. This is described in the second sub-section. Another option is to compile gcc with the POSIX thread model. This is the only way to make use of std::thread in g++ on windows.

Compile GCC/G++ with POSIX thread model

If you want to compile gcc with a C++ compiler and you need libstdc++ with support for std::thread, then you can try the following method to create the cross-compiler. Unfortunately, crossdev has currently some bugs that make this procedure more cumbersome than necessary. With the wrong settings in the hosts make.conf CFLAGS (e.g. -march=native) it is possible to end up with a cross-compiler that compiles for the wrong architecture. Here I describe a process that I used to create a working 64bit cross-compiler for Intel Core2 compatible CPU in Windows.

After the compilation you can check that the thread model is posix by calling the cross-compiler binary with the -v flag.

[..] Thread model: posix

Step 1)

First, make sure CFLAGS in /etc/portage/make.conf is set to compile with -march=core2 or a platform that you know will be supported by the target processor the Windows binaries of your cross compiler will be running on. I compiled a cross-compiler on a Ryzen 2 system with -march=native and had illegal instructions on the target in the libmingwex library.

This will give you a cross-compiler with the unwanted win32 thread model.

[..] Thread model: win32

Step 2)

Next compile the pthread library for the target. I think this library will be compiled for the win32 thread model and will never be used. I’m not sure if this step is really required. Note that this step will overwrite your /etc/portage/package.use/cross-x86_64-w64-mingw32. So better make a backup of this file.

After this step I changed /etc/portage/package.use/cross-x86_64-w64-mingw32 to contain these lines:

Step 3)

Recompile with the cross-compiler with an EXTRA_ECONF variable that will create a cross-compiler of the correct posix-thread model. I read about this procedure in this bugreport: https://bugs.gentoo.org/631460.

Step 4)

Now repeat step 2. To create libpthread but with the cross-compiler of the correct thread-model. Save a backup of /etc/portage/package.use/cross-x86_64-w64-mingw32 before this step.

Make sure /etc/portage/package.use/cross-x86_64-w64-mingw32 contains lines like this:

Verify that the compiler has the posix thread model.

[..] Thread model: posix

The x86_64-w64-mingw32-g++ should support std::thread.

Make sure to revert the change in the CFLAGS variable in /etc/portage/make.conf.

How to link with cross-compiler toolchain

I cross-compiled a C++ program that used sqlite, fftw and glfw. The first two packages can be generated using emerged. I define the following USE flags in /usr/x86_64-w64-mingw32/etc/portage/package.use

For ease of installation I prefer to statically linked cross-compiles binaries. Otherwise the binaries must be packaged with additional dll files.

The sqlite and fftw library can be cross compiled like this:

Unfortunately, Gentoo’s portage system does not allow to cross-compile glfw without X11 dependencies. I therefore compiled this library from source:

The flags for linking the mostly static binary are:

Note that the colon in -l:libsqlite3.a instructs the linker to use the static library file.

I didn’t find a way to statically link with libwinpthread. I have to deliver the binary together with /usr/x86_64-w64-mingw32/usr/bin/libwinpthread-1.dll

Porting POSIX threads to Windows

Windows thread functions seem to work fine with MinGW. The following example code will compile without error:

(The call to Sleep() will make the thread creation a little more closer to POSIX, more in order, and there will not be duplicate runs.)

However, many applications rely upon POSIX threads and do not have code for Windows thread functionality. The POSIX Threads for Win32 project provides a library for using POSIX thread-like features on Windows (rather than relying upon Cygwin). It basically wraps POSIX thread functions to Win32 threading functions ( pthread_create() -> CreateThread() for example). Be aware that not everything is implemented on either end (however do note that Chrome uses this library for threading on Windows). Regardless, many ported applications to Windows end up using POSIX Threads for Win32 because of convenience. With this library you can get the best of both worlds as Windows thread functions work fine as show above.

To get Pthreads for Win32:

  1. Go to the Sourceware FTP and download the header files to your includes directory for MinGW (for me this is /usr/i686-w64-mingw32/usr/include ).
  2. Go to the Sourceware FTP and download only the .a files to your lib directory for MinGW (for me this is /usr/i686-w64-mingw32/usr/lib ).’
  3. At the same directory, get the DLL files (only pthreadGC2.dll and pthreadGCE2.dll; others are for Visual Studio) and place them in the bin directory of your MinGW root (for me this is /usr/i686-w64-mingw32/usr/bin ).

Example POSIX threads code:

With i686-w64-mingw32-objdump -p posix_threads.exe we can see that we need pthreadGC2.dll . If you linked with -lpthreadGCE2 (exception handling POSIX threads), you will need mingwm10.dll , pthreadGCE2.dll , and possibly libgcc_s_sjlj-1.dll (last one only if you do not compile with CFLAG -static-libgcc with g++ ).

Copy the DLL file(s) required to the directory and test with Wine. For example:

If all goes well, you should see output similar to the following:

Wine and %PATH%

Like Windows, Wine supports environment variables. You may specify the path of your DLLs (for example, the MinGW bin directory) in the registry at HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment (for me this value would be Z:\usr\i686-w64-mingw32\usr\bin ). I recommend against this as you might forget to distribute DLLs with your application binaries.

No need for -lm

If you #include and make use of any of its functions, there is no need to link with the standard C math library using the -lm switch with gcc or .

DirectX

DirectX 9 headers and libs are included. Link with -ldx9 . For the math functions (such as MatrixMult , unlike Windows, you need to dynamically link with -ld3dx9d and then include d3dx9d.dll (where you get this file SHOULD be from Microsoft’s SDK). This is the same for DirectX 8.

There is no support for DirectX 10 or 11 yet. Minimal support for Direct2D has been implemented via a patch (search the official mailing list of MinGW).

Removal

If files are left over (such as libraries and things that have been added), a prompt will occur to remove the /usr/i686-w64-mingw32 directory recursively.

Troubleshooting

Emerging a toolchain failed with error: Missing digest for *.ebuild

Add the following to the crossdev overlay metadata:

Источник

Читайте также:  Криптопро удалить контейнер linux
Оцените статью
Тип