简体   繁体   中英

Why does a linux compiled program not work on Windows

I am almost sure my problem is due to the fact that the compiled program is compiled as a linux executable, but I just want to double check this.

#include <stdio.h>
#include <stdlib.h>
int main()
{
    printf("Hello world!\n");
    return EXIT_SUCCESS;
}

The above "program" should compile on Windows and Linux just fine, since it is source code compatible, as there are no operating system specific libraries or anything like that.

Yet, when I type in "c99 hello.c -o hello.exe" on my Linux box, and then transfer that "executable" to a windows machine, it refuses to run. From what I understand, Linux generates an executable file that only runs on linux, so adding ".exe" has no effect. To build that program on Linux for Windows, I would need to recompile that program on a Windows machine? Or is there another simpler method that will work?

Windows and Linux executable files use two different incompatible formats:

On Windows, it is the Portable Executable format .

On Linux it is the ELF (Executable and Linkable Format) .

Each format makes uses of the specificities of the OS they are supposed to run on, so they can't normally be executed on another platform.

Also, an executable only contains a small portion of the code that is executed after it is loaded into memory. An executable file is linked to system libraries that provide most of the functionality that allows the program to interact with the system.
As systems are very different from each other, libraries vary, and a program for say, Linux, cannot be run on FreeBSD despite the latter using also ELF, because they are not linked to the same libraries.

To compile a Windows executable on Linux, a technique known as cross-compilation can be used. A compiler is after all just a program that writes into a binary file, so any compiler can in theory write code for any platform, as long as the target system's libraries are available to be linked against.

The MinGW-w64 project provides a toolchain that allows this. For example, you can install it on debian-based systems using the sudo apt-get install mingw-w64 command.

The installed executables can be used like this:

i686-w64-mingw32-gcc hello.c -o hello32.exe      # 32-bit
x86_64-w64-mingw32-gcc hello.c -o hello64.exe    # 64-bit

Its a compilation situation, diferently from java .exe don't have any virtual machine to interpret the code in diferent OS. Then he needs to have all specific .dll's and lib's from OS to execute the job who is made for.

In .exe all things are made to run on a specific OS, other way in Java a virtual machine is the magic who interpret and run your code on diferents OS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM