且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否允许 C++ 编译器发出不同的机器代码来编译相同的程序?

更新时间:2023-11-10 21:14:58

C++ 标准当然没有规定要防止这种情况发生.然而,实际上,编译器通常是确定性的,因此给定相同的输入,它将产生相同的输出.

The C++ standard certainly doesn't say anything to prevent this from happening. In reality, however, a compiler is normally deterministic, so given identical inputs it will produce identical output.

真正的问题主要是它将环境的哪些部分视为其输入——有一些似乎假设构建机器的特性反映了目标的特性,并改变了它们的输出基于构建环境中隐含的输入"而不是明确声明,例如通过编译器标志.也就是说,即使这样也相对不寻常.规范是输出依赖于显式输入(输入文件、命令行标志等)

The real question is mostly what parts of the environment it considers as its inputs -- there are a few that seem to assume characteristics of the build machine reflect characteristics of the target, and vary their output based on "inputs" that are implicit in the build environment instead of explicitly stated, such as via compiler flags. That said, even that is relatively unusual. The norm is for the output to depend on explicit inputs (input files, command line flags, etc.)

随便,我只能想到一件相当明显的自发"变化的事情:一些编译器和/或链接器将时间戳嵌入到它们的输出文件中,因此输出文件的几个字节将从一个构建更改为下一个构建--但这只会在嵌入文件的元数据中,而不是对生成的实际代码的更改.

Offhand, I can only think of one fairly obvious thing that changes "spontaneously": some compilers and/or linkers embed a timestamp into their output file, so a few bytes of the output file will change from one build to the next--but this will only be in the metadata embedded in the file, not a change to the actual code that's generated.