Mingw

MinGW (historically, MinGW32) is Article description::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.

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

We use a target descriptor to tell, what to build:.

Throughout this article, the 32-bit toolchain has, the 64-bit toolchain has. As we only use MinGW-w64 as runtime,. Don't be confused by, 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.

For example:

The resulting .exe can be found here:

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

Good luck!

Preparation
Crossdev will automatically create and  (or their 32-bit counterparts). Since by default some critical use flags like,   or   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 tool installed, emerge the MinGW toolchain.

Toolchain installation
To build the 64-bit windows toolchain:

To build the 32-bit windows toolchain:

Adding the  or   options may cause issues; they have been known to not build. 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 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.

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 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.

To install:

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):

Portage
The cross environment is a totally independent portage instance, which is configured in.

When building packages, it might just work. Most things do not. Try with  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 should allow most build systems to detect the proper target. Note, some of these may have already been set by :

make.conf tweaks
Mingw64-runtime and the cross-toolchain do not provide any 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  and , 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 :

USE flags can be set globally in or per-package in ; as the builds are for win32 it likely makes sense to globally disable some flags, such as   and globally enable   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  and   values in the CFLAGS variable for the target platform:

Emerging packages
Cross emerging is done by. For example, to emerge the package, use:

Alternatively:

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.
 * An ebuild inherits multilib and specifies  without adding.

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

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 and  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 with , we create

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

This means you can place patches in 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 is empty, we will use this path.

Create the following files:

Portage will then use our custom ebuilds in the folder when we're building for Windows.

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 entry does not suffice to get rid of it. Instead, I recommend overlaying your own ebuild that installs a dummy  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,. This package may be something that can be 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
is a tool that various packages inheriting the gnome eclasses will call in their  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:

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  and , but ncurses-6.0 will not compile.

sys-libs/readline
is another finicky package, in part because it depends on ncurses. Only  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  and.

x11-libs/cairo
Cairo is well supported but the ebuilds currently do not provide a USE flag for the win32 target. Specifying  and ensuring   will address this for now.

If the plan is to emerge, then we abuse the  use flag (both packages do not provide a   use flag) in order to avoid forced X11 dependencies ans set   for both packages. This will enable quartz support via configure options which we have to suppress by specifying.

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 file, which means that this will need to be done by hand using wine, via something like

is possible to circumvent both of these issues by building the gdk-pixbuf with, as this will include the loader code directly in the main gdk-pixbuf dll.
 * 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.

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  and   for gtk+:2 or   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 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 :

GDBM
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.

SDL tutorial example
Emerge SDL:

Try compiling this source code (save to ).

Use the following command to build:

Test with Wine (requires SDL.dll to be somewhere in Wine's, 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  function halts execution for 5000 milliseconds).

Hello World Example
Simple Win32 C program to test installation and function.

To build GUI,  is added (default is  )

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.

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.

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.

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:

Compile with:

(The call to  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 ( -> 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  ).
 * 2) Go to the Sourceware FTP and download only the .a files to your lib directory for MinGW (for me this is  ).'
 * 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  ).

Example POSIX threads code:

Compile with:

With  we can see that we need. If you linked with -lpthreadGCE2 (exception handling POSIX threads), you will need, , and possibly (last one only if you do not compile with CFLAG   with ).

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:

In main: creating thread 0 In main: creating thread 1 Thread #0 responding. In main: creating thread 2 Thread #1 responding. In main: creating thread 3 Thread #2 responding. In main: creating thread 4 Thread #3 responding. Thread #4 responding. Completed join with thread 0, status = 0 Completed join with thread 1, status = 0 Completed join with thread 2, status = 0 Completed join with thread 3, status = 0 Completed join with thread 4, status = 0

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  (for me this value would be  ). I recommend against this as you might forget to distribute DLLs with your application binaries.

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

DirectX
DirectX 9 headers and libs are included. Link with. For the math functions (such as, unlike Windows, you need to dynamically link with   and then include  (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 directory recursively.

Emerging a toolchain failed with error: Missing digest for *.ebuild
Add the following to the crossdev overlay metadata:

External resources

 * Compile for Windows on Linux [BLOGCOMPILER] - Generic introduction to cross-compiling windows binaries.
 * MinGW Hello World [mingw-cross.sourceforge ] - "Hello World" binary guide.
 * GCC and Make Compiling, Linking and Building C/C++ Applications [ntu.edu ] - C/C++ based GCC overview.
 * MinGW/MSYS development environment - Setting up a MinGW/MSYS base system.