如何使用带有Linux子系统的GCC编译Windows的可执行文件?

时间:2021-11-21 02:29:32

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

Windows 10周年更新包括适用于Ubuntu的Linux子系统。我用sudo apt-get install gcc安装了gcc。

I wrote some simple C code for testing purposes:

我为测试目的写了一些简单的C代码:

#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.

并使用gcc -c main.c编译它,但生成了execute(仅限Linux)main.o。如果我运行它./main.o,它会显示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 ?

我的问题是,如何编译main.c以便Windows可以运行它?基本上,如何在Linux子系统中使用GCC生成* .exe文件?

2 个解决方案

#1


41  

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

Linux子系统用作Linux计算机。您只能在其中运行Linux可执行文件,默认gcc会创建Linux可执行文件。

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

要创建Windows可执行文件,您需要安装mingw交叉编译器:

sudo apt-get install mingw-w64

Then you can create 32-bit Windows executable with:

然后,您可以创建32位Windows可执行文件:

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

And 64-bit Windows executable with:

和64位Windows可执行文件:

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.

请注意,这些Windows可执行文件在Linux子系统内部不起作用,仅在其外部。

#2


5  

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

如果你在linux上使用gcc进行编译,它将产生一个ELF文件,而不是PE(windows懂的)文件

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

要在linux中编译windows程序,你可以使用mingw。

#1


41  

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

Linux子系统用作Linux计算机。您只能在其中运行Linux可执行文件,默认gcc会创建Linux可执行文件。

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

要创建Windows可执行文件,您需要安装mingw交叉编译器:

sudo apt-get install mingw-w64

Then you can create 32-bit Windows executable with:

然后,您可以创建32位Windows可执行文件:

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

And 64-bit Windows executable with:

和64位Windows可执行文件:

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.

请注意,这些Windows可执行文件在Linux子系统内部不起作用,仅在其外部。

#2


5  

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

如果你在linux上使用gcc进行编译,它将产生一个ELF文件,而不是PE(windows懂的)文件

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

要在linux中编译windows程序,你可以使用mingw。