This post will explain how to cross-compile a simple C/C++ program using MingW 64-bit toolchain. The exe (Windows Executable) file generated will be tested on the same Ubuntu machine with Wine (Window emulator) program. I am using Wine just for demonstration, you can run the exe file directly on a Windows machine. Let’s start with installing MingW toolchain and Wine on Ubuntu 18.04 version.
Installing Wine and MingW64 on Ubuntu
MingW toolchain comes in both 32-bit and 64-bit architectures, we install 64-bit version for our post. You can install Mingw-64 toolchain using the following command:
$ sudo apt install mingw-w64
$ sudo apt install wine64
Once the above two packages are successfully installed, now we can start cross compiling our C/C++ code.
Cross-compiling C/C++ code
For simplicity I am using very basic “Hello! World” type programs in both C/C++.
Let’s compile the above programs. To compile C program we use:
$ x86_64-w64-mingw32-gcc simple_c.c -o simple_c.exe
and to compile C++ program we use:
$ x86_64-w64-mingw32-g++ simple_cpp.cpp -o simple_cpp.exe
We have successfully cross compiled two programs for Windows on Linux. Now let’s run them using Wine.
Execute EXE using Wine program on Ubuntu
We can run the .exe file on a Linux machine using Wine.
$ wine simple_c.exe
This will print Simple C Program and exit.
$ wine simple_cpp.exe
This will print Simple C++ Program and exit.
Wait! you got an error, something like, “err:module:import_dll Library libstdc++-6.dll not found”? Yes, this is because we are using Wine, an emulator, which is not a complete OS. We have cross-compiled our programs dynamically expecting the execution environment (in our case Windows will provide the necessary DLLs). We have to cross compile our programs statically to include the DLLs as well. But static linking is NOT a correct practice these days. Using -static in your compilation step will remove the above issue.
$ x86_64-w64-mingw32-g++ simple_cpp.cpp -o simple_cpp.exe -static
We will discuss about static and dynamic linking in future articles or else you can start exploring yourself.