Compile C Programs for Windows and Linux

In order to compile a C program on a Linux machine that will run on Windows, cross-compiler software tools need to be installed on the Linux machine. The same C source code can be compiled to run on a Linux machine by using the GCC compiler.

Here we look at how to compile a simple “hello world” C program on a Linux machine for executing on a Linux PC and on a Windows PC.

To compile C programs for Windows and Linux on a Linux machine, the source code needs to be compiled twice, first natively in Linux and then using a cross-compiler on Linux.

In other words a Linux machine is being used for software development and is used to produce:

  • A binary executable file that will run on Linux (using GCC)
  • A binary executable file that will run on Windows (using MinGW-w64)

GCC is the native Linux C compiler and MinGW-w64 is the cross-compiler for compiling a Windows program on Linux.

The Hello World C Program

The C source code for the test program hello.c is listed below. This source code will be compiled to run on Linux and Windows.

Compiling for Linux

The Linux Mint distribution on my PC already has the gcc tools installed, so the C code could be compiled without having to install anything extra.

Compiling for Linux from the command line:

This will produce an executable file called hello that can be run from the command line as follows:

Compiling for Windows

Cross-compiling C source code on a Linux machine to create a binary file that will run on a windows machine requires cross-compiler tools to be installed. Here we use MinGW-w64 and install it from the command line.

Installing MinGW-w64

The following command installs MinGW-w64 on Linux Mint or other Debian based distribution such as Ubuntu.

Compiling for Windows using MinGW-w64

After installing the tools, the hello.c program can be compiled for Windows on the Linux machine. The binary executable file can then be copied over to a Windows machine and run.

To compile for windows:

This binary (hello.exe) should run on both 32-bit and 64-bit Windows. I have only tested it on 64-bit Windows.

To compile for 64-bit Windows only:

I must still test the 64-bit only compile myself to verify that this information is correct.

One thought on “Compile C Programs for Windows and Linux”

  1. I switched to msys2 to install gcc in the most current version that runs on windows:

    c:\>gcc –version
    gcc (Rev3, Built by MSYS2 project) 6.3.0

    …and with that, the Linux command line works as given!

Leave a Reply

Your email address will not be published. Required fields are marked *