c++ - 编译器的 `-O0` 选项和 `-Og` 选项有什么区别?

标签 c++ c debugging gdb compiler-optimization

当我想调试 C 或 C++ 程序时,我被教导使用 -O0关闭优化,和 -ggdb将符号插入为使用 GNU 优化的可执行文件 gdb调试器,我使用(或者,您可以将 -glldb 用于 LLVM/clang 的 lldb 调试器,或者只是 -g 用于一般调试符号,但这显然不如 -ggdb 好......) .然而,我最近偶然发现有人说要使用 -Og (而不是 -O0 ),这让我措手不及。果然,它在man gcc !:

-Og Optimize debugging experience. -Og enables optimizations that do not interfere with debugging. It should be the optimization level of choice for the standard edit-compile-debug cycle, offering a reasonable level of optimization while maintaining fast compilation and a good debugging experience.


那么,有什么区别呢?这是-O0来自 man gcc 的描述:

-O0 Reduce compilation time and make debugging produce the expected results. This is the default.

man gcc明明说-Og不过,“应该是标准编辑-编译-调试循环的首选优化级别”。
这使它听起来像 -O0是真正的“无优化”,而 -Og是“一些优化,但仅限于那些不干扰调试的优化。”这样对吗?那么,我应该使用哪个,为什么?
有关的:
  • 相关,但不是重复的! (仔细阅读,它根本不是重复的):What is the difference between -O0 ,-O1 and -g
  • 我对调试的回答 --copt=与 Bazel 一起使用的设置:gdb: No symbol "i" in current context
  • 最佳答案

    @kaylum 在我的问题下的评论中提供了一些很好的见解!我最关心的关键部分是:

    [-Og] is a better choice than -O0 for producing debuggable code because some compiler passes that collect debug information are disabled at -O0.


    https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#Optimize-Options
    所以,从现在开始我使用 -Og (不是 -O0 )除了 -ggdb .

    UDPATE 2020 年 8 月 13 日:
    见鬼去吧!没关系。我坚持使用 -O0 .
    -Og我收到 <optimized out>Can't take address of "var" which isn't an lvalue.到处都是错误!我不能再打印我的变量或检查它们的内存了!前任:
    (gdb) print &angle
    Can't take address of "angle" which isn't an lvalue.
    (gdb) print angle_fixed_p
    $6 = <optimized out>
    
    -O0但是,一切正常!
    (gdb) print angle
    $7 = -1.34869879e+20
    (gdb) print &angle
    $8 = (float *) 0x7ffffffefbbc
    (gdb) x angle
    0x8000000000000000:     Cannot access memory at address 0x8000000000000000
    (gdb) x &angle
    0x7ffffffefbbc: 0xe0e9f642
    
    所以,回到使用 -O0而不是 -Og这是!
    有关的:
  • [他们也推荐 -O0 , 我同意] What does <value optimized out> mean in gdb?
  • 关于c++ - 编译器的 `-O0` 选项和 `-Og` 选项有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63386189/

    相关文章:

    debugging - Xamarin Studio 5 Unity 加载项存储库

    PHP - error_log() 不会打印到文件

    eclipse - 从 Eclipse 调试 Haxe

    c++ - error C2062 : type 'int' unexpected, 无法解决这个错误

    c - 为什么 gdb 显示错误的变量值?

    c++ - 为什么这个 Rcpp 代码比字节编译的 R 慢?

    java - 为什么额外的数据被写入我的输出流以及如何阻止这种情况?

    c - 一个程序,在整数数组中搜索 10 个数字,以确定它们的总和是否等于给定的 nb

    c++ - 获取连接到图中节点的最大边数

    c++ - 取消 C++ 11 异步任务