用C++编写的程序如何在多个CPU架构上运行?

我有一个 C++ 程序,我想编译成汇编,然后汇编程序将它编译成机器码。

现在,据我所知,为了将汇编代码转换为机器代码,汇编程序需要某种表来将汇编指令映射到实际的机器指令。

汇编程序将使用哪个表?我的 C++ 程序是否有可能不会在所有 CPU 上运行,因为 CPU 使用不同的表,这意味着相同的机器代码将在不同的 CPU 上做不同的事情?

回答

汇编器为它被告知/编程为汇编的任何体系结构进行汇编。由于每种指令集架构 (ISA) 的汇编语言不同,因此您只能为同一架构的一种架构编写汇编程序。通常不可能意外或有意地为错误的体系结构组装程序。

当您使用编译器时,编译器会使用正确的标志调用正确的汇编器来组装它为您告诉它编译的体系结构生成的汇编代码。生成的程序只能在您编译它的 ISA 的处理器上运行。如果您希望程序在不同 ISA 的处理器上运行,则必须为该其他 ISA 编译它。

如果您的程序编写得不好,那么在为您开发它的架构以外的其他架构编译时,它可能无法编译或运行。这样的程序称为不可移植程序。 然而,除非你做了一些奇怪的事情或者对你正在编程的架构的属性做出假设,否则这不太可能发生。

  • @GiorgiLagidze No, that is not right. There are many architectures in popular use. Desktop computers and laptops mostly use amd64 (also known as x86-64), smartphones usually use AArch64 (also known as ARM64), servers some times also use SPARC, mainframes use z/Architecture (also known as S390x). Other architectures like MIPS, RISC-V, ESP32, and ARM32 are also commonly seen. As I tried to say, the reason why C++ programs can be run on any computer is that you can compile them for any architecture. However, you do need to compile them separately for each architecture.
  • @GiorgiLagidze writing code in c++ means that it can be compiled for many platforms, but the resulting binary, will run only for this platform (OS/CPU) combination. Even a specific CPU architecture like `x86-64` can have instructions that might only be available for newer CPUs (like SEE, …).

以上是用C++编写的程序如何在多个CPU架构上运行?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>