How to compile executable for Windows with GCC with Linux Subsystem?

107,357

Solution 1

Linux Subsystem works as a Linux-computer. You can only run Linux executables inside it and default gcc creates Linux executables.

To create Windows executables, you need to install mingw cross-compiler:

sudo apt-get install mingw-w64

Then you can create 32-bit Windows executable with:

i686-w64-mingw32-gcc -o main32.exe main.c

And 64-bit Windows executable with:

x86_64-w64-mingw32-gcc -o main64.exe main.c

Note that these Windows executables will not work inside Linux Subsystem, only outside of it.

Solution 2

If you compile using gcc on linux it will produce an ELF file not a PE (what windows understand) file

To compile a program for windows inside linux you can use mingw.

Share:
107,357
Mikhail
Author by

Mikhail

Just <3 Code

Updated on July 05, 2022

Comments

  • Mikhail
    Mikhail almost 2 years

    Windows 10 Anniversary Update includes the Linux Subsystem for Ubuntu. I installed gcc with sudo apt-get install gcc.

    I wrote some simple C code for testing purposes:

    #include <stdio.h>
    int main(void){
        printf("Hello\n");
        return 0;
    }
    

    And compiled it with gcc -c main.c but the execute (Linux only) main.o is generated. If I run it ./main.o, it displays Hello.

    My question is, how can I compile main.c so that Windows can run it? Basically, how do you generate a *.exe file with GCC in Linux Subsystem ?

  • sam msft
    sam msft almost 7 years
    The man page for gcc seems to imply that there are some options for making Windows console and windowed exes. Is there any reason why they wouldn't work? -mconsole -mwindows
  • Markus Laire
    Markus Laire almost 7 years
    I don't have much experience with creating Windows apps, so I don't know the details of those compiler options. Still those Windows-specific options will only work with *-mingw32-gcc compilers and not default gcc which is creating Linux executables.
  • sam msft
    sam msft almost 7 years
    It seems like x86_64-w64-mingw32-gcc is changed such that it is designed to use the windows C runtime (MSVCRT.DLL) and other core Windows libraries instead of the standard C libs gcc links (presumably whatever is in /lib?).
  • user12346352
    user12346352 over 5 years
    it seems to work but how can compile the file to .exe if the .c needs a .txt file as parameter
  • hippietrail
    hippietrail over 4 years
    I doubt this is exactly correct. It says you "need to" use mingw. Surely that's only one option. GCC is famously supposed to be able to cross-compile between anything so surely it can also cross-compile x86-PE on an x86-ELF system? I don't know how to do it but it seems shocking if it's impossible.
  • Jackie
    Jackie about 2 years
    Would there be any advantage to using mingw over cygwin? I was trying to avoid either.