如何禁用 gcc 中的编译器优化?
我正在尝试学习汇编语言。我已经搜索并找到了如何反汇编 .c
文件,但我认为它会产生该程序的一些优化版本。有什么方法可以让我看到与我的 C 文件相对应的确切汇编代码。
I am trying to learn assembly language. I have searched and found how to disassemble a .c
file but I think it produces some optimized version of the program. Is there any way so that I can see the exact assembly code which corresponds to my C file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
gcc 选项
-O
启用不同级别的优化。使用-O0
禁用它们并使用-S
输出汇编。-O3
是最高级别的优化。从 gcc 4.8 开始,优化级别
-Og
可用。它可以实现不干扰调试的优化,并且是标准编辑-编译-调试周期的推荐默认值。要将程序集的方言更改为 intel 或 att,请使用
-masm=intel
或-masm=att
。您还可以使用
-fname
手动启用某些优化。有关更多信息,请参阅 gcc 手册。
The gcc option
-O
enables different levels of optimization. Use-O0
to disable them and use-S
to output assembly.-O3
is the highest level of optimization.Starting with gcc 4.8 the optimization level
-Og
is available. It enables optimizations that do not interfere with debugging and is the recommended default for the standard edit-compile-debug cycle.To change the dialect of the assembly to either intel or att use
-masm=intel
or-masm=att
.You can also enable certain optimizations manually with
-fname
.Have a look at the gcc manual for much more.
要在不进行复制省略的情况下进行测试并查看复制/移动构造函数/运算符的实际操作,请添加“-fno-elide-constructors”。
即使没有优化(-O0),GCC 和 Clang 仍然会执行复制省略,这在某些情况下会产生跳过复制/移动构造函数的效果。有关复制省略的详细信息,请参阅此问题。
然而,在 Clang 3.4 中,它确实触发了一个错误(未调用构造函数的无效临时对象),该错误在 3.5 中已修复。
To test without copy elision and see you copy/move constructors/operators in action add "-fno-elide-constructors".
Even with no optimizations (-O0 ), GCC and Clang will still do copy elision, which has the effect of skipping copy/move constructors in some cases. See this question for the details about copy elision.
However, in Clang 3.4 it does trigger a bug (an invalid temporary object without calling constructor), which is fixed in 3.5.
对于 gcc,您希望省略传递给编译器的任何 -O1 -O2 或 -O3 选项,或者如果您已经拥有它们,则可以附加 -O0再次将其关闭的选项。它还可能帮助您添加 -g 进行调试,以便您可以在调试器中看到 c 源代码和反汇编的机器代码。
另请参阅:http://sourceware.org/gdb/onlinedocs/gdb/Optimized-Code.html
For gcc you want to omit any -O1 -O2 or -O3 options passed to the compiler or if you already have them you can append the -O0 option to turn it off again. It might also help you to add -g for debug so that you can see the c source and disassembled machine code in your debugger.
See also: http://sourceware.org/gdb/onlinedocs/gdb/Optimized-Code.html
使用命令行选项
-O0
(-[大写o][零])禁用优化,使用-S
获取汇编文件。请参阅此处了解更多 gcc 命令行选项。Use the command-line option
-O0
(-[capital o][zero]) to disable optimization, and-S
to get assembly file. Look here to see more gcc command-line options.您还可以使用 #pragma GCC Push_options 在内部控制优化
You can also control optimisations internally with #pragma GCC push_options
很久以前的事了,但仍然需要。
Long time ago, but still needed.
如果使用 gcc 命令行传递 -O0,则可以禁用优化。
例如,将 .C 文件转换为 .S 文件调用:
gcc -O0 -S test.c
You can disable optimizations if you pass -O0 with the gcc command-line.
E.g. to turn a .C file into a .S file call:
gcc -O0 -S test.c