Is there a flag or other reliable method to detect if a compiled C++ binary was compiled with optimizations?
I'm okay with compiler-specific solutions.
Edit: This is for a build deployment system, which could accidentally deploy binaries that were not built properly. A water-tight solution is unlikely, but it will save some pain (and money) if this can be detected some of the time.
The compiler will often be gcc, sometimes sun, and if there's a MSVC solution, I don't want to rule that out for the benefit of the community.
Recent versions of GCC have a way to report which flags were used to compile a binary (third bullet point).
There is a related command line switch (--fverbose-asm) that "only records the information in the assembler output file as comments, so the information never reaches the object file." The --frecord-gcc-switches switch "causes the command line that was used to invoke the compiler to be recorded into the object file that is being created."
If I would be given this task and it would prove it is a reasonable task (see below), I would perform "a frequency analysis" of the patterns seen in the executable disassembly. As a programmer I am able to distinguish between an optimized and an unoptimized (debug) code at a first glance. I would try to formalize the decision process, with Visual Studio and the x86 platform the typical features seen in an unoptimized exe would be:
This is definitely not 100 %, but with longer exe I would expect the results to be quite reliable.
I assume for other x86 platforms including GCC the rules will be similar, if not the same, and for other platforms similar rules can be found.
Other heuristics like detection of the runtime library may work as well, depending on compiler settings.
That said, I think such task "smells" and under most circumstances it would be sensible to avoid it completely. If you will provide the real reason behind such task, it is very likely some sensible solution will be found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With