C++ 不是平台无关的,因为它需要编译成本地代码,并且需要针对不同的 CPU 架构实现不同的编译器。
C++ 编译器仅将代码翻译成机器语言或 native 代码。此 native 代码由处理器执行。
根据我在网上读到的内容,一个 Java 程序最初是由 java 编译器“javac”编译成字节码的。然后,Java 虚拟机逐行解释(并执行)此字节码。
我几乎没有疑问。
1) If C++ is not platform independent because different compilers need to be designed for different CPU architectures, then doesn't JVM differ from one hardware to another as well?
2) If I wrote a C++ code and compiled and executed it on Machine 1 and Machine 2, the output produced will be the same. Similarly, if I write a Java program and execute it on two different machines, the output will still be the same. Why the extra step of bytecode generation?
3) I read somewhere that interpreters, unlike compilers, actually execute a program by emulating a virtual machine. Does it mean that JVM actually executes the bytecode and not just interprets it into native code?
最佳答案
C++是一次编写,随处编译(至少在理论上,说起来容易做起来难,但它做到了)
Java是一次编译,随处运行(前提是安装了JVM,系统之间还是存在差异,无法完全隐藏)
If C++ is not platform independent because different compilers need to be designed for different CPU architectures, then doesn't JVM differ from one hardware to another as well?
JVM 不同,但字节码不一定。 C++ 可以编写一次,但通常具有特定于平台的代码。这不一定是个问题,但您可以预料到代码必须经过测试,这是针对其所针对的每种系统风格编写的自定义代码。
If I wrote a C++ code and compiled and executed it on Machine 1 and Machine 2, the output produced will be the same. Similarly, if I write a Java program and execute it on two different machines, the output will still be the same. Why the extra step of bytecode generation?
Java 只需要编译一次。您可以在二十年前在运行 Windows 95 的 32 位 Windows 平台上使用 Java 1.0 编译的 JAR,并在没有源代码或不知道其编译方式的情况下立即使用它,在运行 Linux 的 64 位 ARM 处理器上,它将使用该处理器的最新优化和指令集。
对于 C++,如果您采用 20 年前在 Windows 95 上编写的程序,如果不在 Linux 的 64 位 ARM 处理器上大量工作和测试,它可能无法编译。
I read somewhere that interpreters, unlike compilers, actually execute a program by emulating a virtual machine. Does it mean that JVM actually executes the bytecode and not just interprets it into native code?
JVM 最初解释,快速编译,然后变慢(在 OpenJDK 中称为 C1),然后更积极地重新优化(称为 C2)它经历了 4 个不同的编译级别,它可以取消优化代码以获得它根据不断变化的使用情况甚至更改代码重新优化。
关于java - 如果 JVM 实现因一台机器而异,字节码生成如何使 Java 平台独立?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32125611/