C语言 如何使用带有 Linux 子系统的 GCC 为 Windows 编译可执行文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38786014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compile executable for Windows with GCC with Linux Subsystem?
提问by Mikhail
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.
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.cbut the execute (Linux only) main.ois generated. If I run it ./main.o, it displays Hello.
并编译它,gcc -c main.c但main.o会生成执行(仅限 Linux)。如果我运行它./main.o,它会显示Hello.
My question is, how can I compile main.cso that Windows can run it? Basically, how do you generate a *.exefile with GCC in Linux Subsystem ?
我的问题是,我如何编译main.c以便 Windows 可以运行它?基本上,您如何*.exe在 Linux 子系统中使用 GCC生成文件?
回答by Markus Laire
Linux Subsystem works as a Linux-computer. You can only run Linux executables inside it and default gcccreates 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 子系统内部运行,只能在其外部运行。
回答by david
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。

![C语言 Valgrind 在 C 中无效的 free()/delete/delete[]/realloc()](/res/img/loading.gif)