Why a program compiled on Linux does not work on Windows

I am pretty sure that my problem is that the compiled program was 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 be easy to compile on Windows and Linux, since it is compatible with the source code, since there are no specific libraries for a specific operating system or something like that.

However, when I enter "c99 hello.c -o hello.exe" into my Linux block and then transfer this "executable" to the Windows machine, it refuses to start. From what I understand, Linux generates an executable that only works on Linux, so adding ".exe" has no effect. To create this program for Linux for Windows, will I need to recompile this program on a Windows computer? Or is there another simpler method that will work?

+8
c linux windows
source share
2 answers

The Windows and Linux executables use two different incompatible formats:

On Windows, this is the Portable Executable format .

On Linux, this is ELF (Executable and Bound Format) .

Each format uses the features of the OS on which they should work, so they usually can not be run on another platform.

In addition, the executable file contains only a small part of the code that is executed after it is loaded into memory. The executable file is associated with system libraries that provide most of the functions that allow the program to interact with the system.
Since the systems are very different from each other, the libraries are different, and the program, say, Linux, cannot be run on FreeBSD, despite the fact that the latter also uses ELF because they are not connected to the same libraries.

To compile the Windows executable on Linux, you can use a method known as cross-compilation. A compiler is, after all, just a program that writes to a binary file, so any compiler can theoretically write code for any platform if the target system libraries are available.

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

Installed executables can be used as follows:

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

In its compilation situation other than java.exe, there is no virtual machine to interpret the code in another OS. Then it must have all the specific .dll and lib from the OS in order to complete the task for which it was created.

In .exe, everything is done to work on a specific OS, otherwise in Java a virtual machine is the magic that interprets and runs your code on different operating systems.

0
source share

All Articles