Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can C code be run on different processors?

As I understand it, C code is compiled to machine (assembly) code on someone’s machine, and it becomes an exe file that can be run on lots of different processors (machines). But since different processors have their own unique assembly code how can this code run? Wouldn't the compiled exe only be able to run on one type of processor?

like image 224
Melkor Avatar asked Feb 24 '16 09:02

Melkor


1 Answers

When you compile a program to machine code, you have to select a machine code instruction set, perhaps a mode in which to run the machine (if applicable), and a format in which the resulting code is stored.

All those choices limit the target platform on which the code can be executed.

  • The instruction set broadly depends on the type of CPU: x86 ("IBM-compatible"), PowerPC, ARM, MIPS, DEC Alpha, Motorola 68k, ... Within each CPU family, there are many sub-features and generations to choose from (e.g. for x86, there are i386, SSE, AVX, ...). Newer CPUs may be able to execute code limited to older generations, so there may be a common subset.

  • The processor mode on x86 depends on the environment: real mode for MS-DOS programs and anything you run on boot-up, protected mode, different addressing modes may be available in some situations (unreal mode)...

  • The binary format needs to be recognized by the operating system, or more generally by what ever loading mechanism you have: PE for Windows, ELF for contemporary Linux, a.out in the old days, ... An operating system may provide loaders for multiple binary formats.

This is only the most basic level of platform parameters that you choose when compiling, and your program will only run on platforms that agree on this choice. However, there are many more practical limitations for real-world programs, such as the OS systems interface and the availability of framework libraries, that also need to match. For example, while it's not hard to read and run Windows PE binaries in Linux, the code contained therein doesn't make sense on Linux because it uses Windows-specific software interrupts. However, by intercepting and translating those, it is quite possible to run those binaries on Linux after all.

like image 83
Kerrek SB Avatar answered Oct 20 '22 06:10

Kerrek SB