Search code examples
buildcompilation

will compiling with the same source, compiler and library version result in exactly the same binary


I would like to know if I get exactly the same binary result if I compile with:

  1. the same source code
  2. the same compiler, version, command
  3. the same library

Or are there other constraints as well that might result to different binaries like:

  • time when the source was compiled
  • system, kernel version
  • other build tools

Solution

  • There's no guarantee that just by fixing the code, libraries and compiler that you will get the same output. As you've identified, the environment in which the compiler is run may have an impact:

    • It's not just a compiler, but a whole toolchain that you need to keep static (linkers, assemblers, etc).
    • Does the toolchain use dynamic libraries which may be updated over time?
    • What about environment variables?
    • Are you running as the same user? With the same privileges.

    Even if you could find and control all of these features, compilation may not be deterministic. Here's a concrete example from the GCC 3.3 documentation (note the wording has changed in recent versions):

    -fno-guess-branch-probability

    Do not guess branch probabilities using a randomized model. Sometimes gcc will opt to use a randomized model to guess branch probabilities, when none are available from either profiling feedback (-fprofile-arcs) or __builtin_expect. This means that different runs of the compiler on the same program may produce different object code.

    In a hard real-time system, people don't want different runs of the compiler to produce code that has different behavior; minimizing non-determinism is of paramount import. This switch allows users to reduce non-determinism, possibly at the expense of inferior optimization.