关于 c :使用 -g 编译本身会降低性能吗?

Does compiling with -g, in itself, degrade performance?

本问题已经有最佳答案,请猛点这里访问。

(这是一个关于 gcc 和 clang 的问题,但可能适用于其他编译器。)

如果我编译我的 C 或 C 代码,并使用 -g 开关生成调试信息,这本身是否会以任何方式降低已编译程序的性能...

  • 最小优化(-O0)?
  • 最大优化(-O3)?
  • 注意:我不是说必须解析/加载可执行文件的性能损失,由于额外的内容,它会更大;我的意思是运行的代码。


    我认为没有任何性能差异。实际上,根据此处的文档,生成的代码是相同的,并且 -g 可与 -O 一起使用。此外,调试符号不会写入代码,而是写入另一个称为"调试部分"的部分,该部分甚至不会在运行时加载(仅由调试器)

    -g 不会改变运行的优化或生成的代码。
    这是此处所述的 gcc 政策

    但是,请注意相同的文档指出:

    The shortcuts taken by optimized code may occasionally be surprising:
    some variables you declared may not exist at all; flow of control may
    briefly move where you did not expect it; some statements may not be
    executed because they compute constant results or their values are
    already at hand; some statements may execute in different places
    because they have been moved out of loops. Nevertheless it is possible
    to debug optimized output. This makes it reasonable to use the
    optimizer for programs that might have bugs.

    所以最终调试永远不会损害您的优化,但相反的是错误的,使用 -O3 可能会降低您的调试信息(例如删除无用的变量)。

    请注意,在这种情况下使用 -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.

    但是这会影响性能,因为一些会干扰调试的优化通道不会完成。

    编辑:

    链接和引号回答了您对 gcc 的问题。它可能不适用于其他编译器,例如 clang
    但是我也找到了一些 clang 的文档。
    例如这里:

    Basically, the debug information allows you to compile a program with
    "-O0 -g" and get full debug information, allowing you to arbitrarily
    modify the program as it executes from a debugger. Compiling a program
    with"-O3 -g" gives you full debug information that is always
    available and accurate for reading (e.g., you get accurate stack
    traces despite tail call elimination and inlining), but you might lose
    the ability to modify the program and call functions where were
    optimized out of the program, or inlined away completely.


    -g 标志将调试信息添加到二进制文件中。这存在于 .text CPU 运行位的可执行文件的单独部分(.stab.stabstr)中。在调试器之外运行时,操作系统加载器不会加载调试部分。还可以使用 strip 实用程序轻松去除调试信息,以生成与未使用 -g 标志编译的二进制文件相同的二进制文件。

    然而,通常当您想要调试内容时,您将在没有优化和 NDEBUG 预处理器宏的情况下进行编译。然而,这些事情不受 -g 标志的控制。


    如果您在调试器之外运行它,则不会有任何性能损失。调试符号是为了帮助调试。两种情况下生成的代码应相同。