GCC pragma optimize 不会覆盖 `-Og` 命令行设置

GCC pragma optimize does not override `-Og` command line setting

对于单个函数或编译单元,是否可以使用 O2/O3 覆盖 -Og GCC 优化级别?

如果在命令行中使用-Og,编译器似乎不会遵守#pragma GCC optimize("O2")__attribute__((optimize("O2"))

例如,this function doing saturating addition 在 ARM Cortex-M4 上。仅当我使用 -O2 编译时,它才会编译为 ssat,但最右边的编译器使用 -Og 并忽略 pragma。

另一方面,使用较低优化级别编译指示有效,即指定O0作为编译指示覆盖命令行中的-Og

这是预期的行为吗?

Is it possible to override the -Og GCC optimization level with O2/O3 for a single function or compilation unit?

是也不是。 The documentation for the optimize attribute,pragma 文档所指的是:

The optimize attribute is used to specify that a function is to be compiled with different optimization options than specified on the command line.

因此属性或编译指示确实覆盖了命令行。然而,这适用于 per-function 级别,而 the -Og option has both per-function and global effects:

Like -O0, -Og completely disables a number of optimization passes so that individual options controlling them have no effect.

因此,虽然使用属性或 pragma 设置优化级别 O2O3 确实会打开该级别中包含的所有单独优化,但这样做可能不会产生全部效果在命令行上设置它们就可以了。

另请注意文档的警告

The optimize attribute should be used for debugging purposes only. It is not suitable in production code.

我认为你 调试,因为这是 -Og 的目的,但你应该从该评论中得到的是你不应该依赖关于强制打开或关闭优化选项的技术。正如您所发现的,它可能不会有效或完全地做到这一点。

Is this expected behavior?

您描述的行为似乎与文档一致,尽管它们没有指定细节。但是,您描述它的方式是,当在命令行上设置 -Og 时 pragma 被忽略——这不是预期的,我认为不准确。