Call Windows APIs with C++ using MinGW
This can be accomplished without Cygwin/MSYS.
Example Program
Let's assume we want to build the following program test.c
. It displays a message box, sleeps for two seconds and displays another message box.
Using #include <windows.h>
enables us to call Windows APIs.
#include <windows.h>
// MessageBox: https://msdn.microsoft.com/en-us/library/windows/desktop/ms645505(v=vs.85).aspx
// Sleep: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686298(v=vs.85).aspx
int main(void)
{
MessageBox(NULL, "test", "test", 0x20);
Sleep(2000);
MessageBox(NULL, "test2", "test2", 0x06);
return 0;
}
Using win-builds.org
- Download the installer from http://win-builds.org/.
- Run the installer. Select
Native Windows
andi686
arch. - Choose a path for 32-bit installation. For example:
c:\mingw\x86
. - Click on
Process
to start downloading. - If there's an error during a download, the tool will just stop. If the tools is not doing anything for a while, check the errors in command prompt. If this happens:
- Close the installer.
- Navigate to
c:\mingw\x86\
and runyypkg-1.5.0.exe
(version number might be different). - Click on
Process
again to continue downloading. - Rinse and repeat until everything is downloaded
- Go back to step 2, re-run the installer. Select
Native Windows
andx86_64
. - Choose a path for 64-bit installation (must be on a Windows 64-bit machine). For example
c:\mingw\x64
. - Follow steps 4 and 5 until everything is installed.
- Now we can build the program for both architectures (switches are optional).
- 32-bit:
cd c:\mingw\x86\bin
c:\mingw\x86\bin\> gcc.exe -g c:\path\to\test.c -o c:\path\to\test-32.exe -w -mwindows
- 64-bit:
cd c:\mingw\x64\bin
c:\mingw\x64\bin\> gcc.exe -g c:\path\to\test.c -o c:\path\to\test-32.exe -w -mwindows
- 32-bit:
- If you see yourself building only one architecture, add the corresponding
bin
directory to PATH.
Using MinGW (32-bit)
- Install MinGW setup:
- Install
mingw32-gcc-g++
using the package manager. - Add
C:\MinGW\bin
to PATH. - Do
gcc -g test.cpp -o text.exe -w -mwindows
(mix and match switches).