Installing mingw32 on linux

В поддержку Qt

статьи в помощь разработчику

Установка MinGW

Компилятор MinGW является важным компонентом среды разработки приложений для Windows с использованием библиотеки Qt, если конечно Вы выбрали именно такой вариант, а не альтернативный, использующий Microsoft Visual Studio. Данная статья призвана оказать помощь в установке компилятора.

В Linux устанавливать компилятор MinGW может потребоваться только в том случае, если Вы собираетесь производить сборку приложений для Windows. О том как это делается, в том числе и непосредственно сам процесс установки MinGW, подробно изложено в посвященной этой теме статье.

При установке Qt 5 имеется возможность установить и требуемую версию компилятора MinGW (см. здесь). Для независимой установки выполняются действия, описанные ниже.

1. Скачиваем отсюда готовую сборку MinGW 4.9.2

i686-4.9.2-release-posix-dwarf-rt_v3-rev1.7z 48 MB
(именно 1-я «ревизия» устанавливается с Qt 5.5.1)

2. В архиве лежит папка mingw32 , распаковываем ее в папку C:\Qt и переименовываем, например, в mingw-4.9.2 .

Данная версия замечательна тем, что вместе с MinGW устанавливается и работоспособный MSYS, без которого никак не обойтись. Процесс установки совсем несложный.

1. Скачиваем с сайта разработчика файл установщика онлайн

mingw-get-inst-20120426.exe 647 KB

2. Запускаем установщик и следуем инструкциям. При запросе

Use pre-packaged repository catalogues 20120426
Download latest repository catalogues

следует выбрать первый из предложенных вариантов установки. Путь установки, предложенный по умолчанию, лучше изменить, но пробелы в нем должны отсутствовать. Пусть будет, например, C:\Qt\mingw-4.6.2 . Группу создаваемых ярлыков назовем MinGW 4.6.2 . Когда будет предложено выбрать устанавливаемые компоненты, следует обязательно отметить пункты C++ Compiler и MSYS Basic System . Последний потребуется для сборки отладчика GDB (см. статью). Во время работы установщика в консольном окне будут отображаться выполняемые действия – загрузка компонентов, их распаковка, настройка и т.п.

Основным востребованным инструментом данной версии MinGW будет оболочка командной строки Unix-подобной среды. Запустить ее можно, воспользовавшись пунктом главного меню MinGW Shell из созданной при установке группы ярлыков или выполнив в командной строке Windows

3. В заключение добавим несколько пакетов, которые не вошли в состав ядра MSYS, но могут оказаться востребованными. Речь идет о библиотеке bz2 , а также утилитах patch и unzip . Для их установки запускаем MinGW Shell и вводим команды

mingw-get install msys-libbz2
mingw-get install msys-patch
mingw-get install msys-unzip

Установить перечисленные выше пакеты можно добавить и вручную, как предлагалось в предыдущей редакции статьи.

Данная версия MinGW требуется для использования с библиотекой Qt 4.8.5 и ниже, например, для поддержки старых проектов, время модернизации которых под Qt 5 не настало. Для установки выполняются действия, описанные ниже.

1. Скачиваем отсюда или отсюда готовую сборку

MinGW-gcc440_1.zip 34 MB

Следует отметить, что в настоящее время приведенные здесь ссылки пожалуй являются одними из немногих рабочих. Спасибо за них сайтам code.google.com и code.x2go.org.

2. В архиве лежит папка mingw , распаковываем ее в папку C:\Qt и переименовываем, например, в mingw-4.4.0 .

Это новая редакция статьи, старая редакция доступна по ссылке.

Источник

How to build using mingw32 on Linux? #154

Comments

Hacksawfred3232 commented Jul 31, 2019

Requesting this because I need rdiff as part of a requirement on a python lib I’m building. The API that my lib talks to requires a rsync signature file along with the main file or a rsync delta when uploading to their services. I only have a small server with about 3 GB of memory and a old processor, so I can’t use WINE. Don’t even know if cygwin works under wine and if anything that is built under cygwin can be ran on plain Windows.

The text was updated successfully, but these errors were encountered:

mosolovsa commented Aug 6, 2019 •

I’m not sure if this is what you want, but:

directory with CMakeFile.txt located

mkdir build
cd build
cmake -DMINGW=ON -DCMAKE_TRY_COMPILE_TARGET_TYPE=STATIC_LIBRARY -DCMAKE_C_COMPILER=i686-w64-mingw32.static-gcc ..

-DCMAKE_TRY_COMPILE_TARGET_TYPE=STATIC_LIBRARY — to prevent compiling simple executable and trying to run it during cmake build.
i686-w64-mingw32.static-gcc must be path to your mingw c compiler.

dbaarda commented Aug 24, 2019

With the merge of #161 a bunch of problems building with MinGW have been fixed. It should now be possible to build it using mingw32 and cmake without forcing a static library.

Please try it and let us know if there are any remaining problems or tricks to make it work. I welcome any pull requests with documentation to make this easier.

Hacksawfred3232 commented Sep 29, 2019

Sorry for not responding sooner! Trying to compile with mosolovsa’s command minus the «STATIC_LIBRARY» flag returns this:

(Oh and by the way, static-gcc does not exist on my system)

deajan commented Sep 30, 2019

I also cannot build latest librsync 2.1.0 with mingw.

I need to build a static librsync lib using mingw, so I change CMakeLists.txt from

This used to work with librsync 2.0.2 but does not anymore.

I’ve applied patch from #161 and tried again, I get the same following output:

I’ve also tried to build current git master, got the same results.
Does anyone have an idea what’s changed so that static builds fail ?

dbaarda commented Oct 1, 2019

To make librsync static compile you need to also add

target_compile_options(rsync PRIVATE -DLIBRSYNC_STATIC_DEFINE)

This ensures that LIBRSYNC_EXPORT is defined correctly for static linking in librsync_export.h.

However, I’d also like to figure out why dynamic linking is not working.

deajan commented Oct 1, 2019

@dbaarda static compilation now works with the option you provided.
Btw, shared compilation works out of the box for me with current git master.
Maybe you could consider releasing librsync 2.1.1 soon, or at least an interim build with the mingw fixes applied ?

Thank you for your help.

dbaarda commented Oct 2, 2019

Do we want to make static compilation a CMake configurable option? It looks like the way to do this is make BUILD_SHARED_LIBS an option and remove the explicit SHARED|STATIC from add_library();

Читайте также:  Github windows что это

We’d also need to conditionally set LIBRSYNC_STATIC_DEFINE if BUILD_SHARED_LIBS is OFF.

dbaarda commented Oct 2, 2019

It’s not entirely clear to me what is/isn’t working with git master right now.

deajan: are you using mingw on windows, or cross-compiling to windows on linux? Could you give a quick

5 line howto on what you are doing that works?

Hacksawfred3232: Is it still broken for you? The following seems to have good information on how to make mingw cross-compiling work with cmake;

I’m happy to accept pull requests to make this easier, either by documenting it better, or improving our cmake configuration for that use-case.

I also have a pull request on the way to add BUILD_SHARED_LIBS as a cmake option for building librsync as a static library.

Источник

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) .
Читайте также:  Windows svr std 2019 64bit russian 1pk dsp oei dvd 16 core p73 07797

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.

Читайте также:  Можно ли удалить папки с обновлениями 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:

Источник

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