Installing and Using the MinGW Cross-Compiler on Mac OS X

07 Dec 2004, 15:13 PST

MinGW supplies header files, import libraries, and a compiler tool-chain based on GNU cc and binutils for building native Windows executables and libraries with no dependencies on third party libraries.

I am using the MinGW tool-chain to compile the Win32 port of OpenDarwin libFoundation. To cross-compile the library on my Mac OS X machine, I created DarwinPorts Portfiles for the MinGW tool-chain.

In this article I'll document how to install the MinGW ports, build a "Hello, World" example, and run the result on a x86 machine using Wine.

To install the MinGW ports, you'll first need a working, up-to-date installation of DarwinPorts. Installation instructions are available here, and instructions on updating your installation are available here.

Once you have a working, up-to-date DarwinPorts installation, issue the following command to build and install the MinGW compiler, linker, headers, and libraries:

port -v install i386-mingw32-gcc

This will take some time to build.

Once the installation is complete, the new compiler will have been installed as i386-mingw32-gcc. Using your new compiler, you can build a graphical "Hello, World" executable for Windows.

Save the following file as winhello.c:

/*
 * Hello, World for Win32
 * gcc winhello.c -o winhello.exe
 */
#include <windows.h>
int main(int argc, char *argv[])
{
	MessageBox(NULL, "Hello, world!", "Hello, world!", MB_OK);
	return 0;
}

To build, execute the following command:

landonf@darwin:~> i386-mingw32-gcc winhello.c -o winhello.exe

If the build completes successfully, the compiler will create "winhello.exe" in the current working directory.

landonf@darwin:~> file winhello.exe  
winhello.exe: MS Windows PE 32-bit Intel 80386 console executable not relocatable

The executable will run natively on Windows, or alternatively, you can test it by using Wine on a x86 machine. The Darwine project is working on integrating Wine with a x86 emulator to support running of x86 Win32 executables on Darwin/PPC; however, at the time of this writing that functionality has still not been completed.

I used Wine on my FreeBSD test machine to run the Hello Word executable.

landonf@freebsd:~> wine winhello.exe

winhello.exe screenshot

More information on the MinGW project is available from their web site.