Sanjaya Pandey Sanjaya Pandey - 3 months ago 13
C++ Question

Is C++ platform dependent?

Can we say that C++ is platform dependent?

I know that C++ uses compiler, and those compiler are different for different platforms. When we compile C++ code using compiler for example: on Windows, .EXE format file created.

Why is an .EXE file OS/Platform dependent?

What is the format inside .EXE files?

Why can't we run it on other platforms?


This is actually a relatively extensive topic. For simplicity, it comes down to two things: operating system and CPU architecture.

First of all, *.exe is generally only Windows since it is binary code which the windows operating system knows how to execute. Furthermore, the operating system knows how to translate this to the proper code for the architecture (this is why Windows is "just compatible"). Note that a lot more is going on, but this is a (very) high-level abstraction of what is going on.

Now, compilers will take C++ code and generate its corresponding assembly code for the architecture (i.e. x86, MIPS, etc.). Usually the compiler also has an assembler (or one which it can rely on). The assembler the links code and generates binary code which the hardware can execute. For more information on this topic look for more information on co-generation.

Additional Note

Consider Java which is not platform-dependent. Java compilers generate Java bytecode which is run on the Java virtual machine (JVM). It is important to notice that any time you wish to run a Java application you must run the Java virtual machine. Since the precompiled JVM knows how to operate on your operating system and CPU architecture, it can run its Java bytecode and effectively run the corresponding actions for your particular system.

In a compiled binary file (i.e. one from C++ code), you have system bytecode. So the kind of instructions which Java simulates for you are directly hard-coded into the .exe or whatever binary format you are using. Consider the following example:

Notice that this java code must eventually be run in the JVM and cannot stand-alone.

Java Code:
System.out.println("hello") (To be compiled)

Compiled Java bytecode:
Print "hello" (To be run in JVM)

(... some translation, maybe to architecture code - I forget exactly ...)
system_print_code "hello" (JVM translation to CPU specific)

Versus the C++ (which can be run in stand-alone mode):

C++ Code:
cout<< "hello";

Architecture Code:
some_assembly_routine "hello"

Binary output:
system_print_code "hello"