Clang: 不要优化给定的文件

huangapple go评论104阅读模式
英文:

Clang: Don't optimize a given file

问题

当使用Clang编译时,我可以将optnone属性添加到一个函数上,以便在编译时不进行优化。

[[clang::optnone]]
void foo() {
    // 此处不应用任何优化
    ...
}

void bar() {
    // 而其他函数仍然会被优化
}

在使用GDB进行调试时,这非常有用。对于那些因为太大而无法完全以调试模式(llvm)编译的程序,我可以选择使用CMake设置为RelWithDebInfo,然后将属性添加到感兴趣的一些函数中,从而在这些地方获得一致的调试信息,而不必在内联值之间跳来跳去。

是否有一种等效的方法可以在调试模式下编译给定文件中的所有函数,而无需手动将属性添加到每个函数中?

英文:

When compiling with Clang, I can add the optnone attribute to a function to compile it without optimizations

[[clang::optnone]]
void foo() {
    // no optimizations applied in here
    ...
}

void bar() {
    // while other functions are still optimized
}

This is really useful when debugging with GDB. On programs that are too large to be practically compiled entirely in debug mode (llvm), I can instead compile with CMake set to RelWithDebInfo, add the attribute to some functions of interest, then get a consistent debug in those places without jumping around and fighting inlined values.

Is there any equivalent way to compile all functions in a given file in debug mode, without manually adding the attribute to every function?

Cheers

答案1

得分: 2

  1. 编译您的源文件单独生成目标文件(这在大多数构建设置中会自动完成);然后针对特定的目标文件设置自定义优化设置。例如:
cc -O3 file1.c -c -o file1.o
cc -O0 -g file2.c -c -o file2.o

将仅优化 file1.c 而不是 file2.c。这适用于任何编译器。

  1. 使用基于范围的优化指令,这是 Clang 的扩展。编写 #pragma clang optimize off 可以在那一点之后禁用优化,而 #pragma clang optimize on 可以重新启用它们。例如,只需在文件顶部添加 #pragma clang optimize off 将禁用整个文件的优化。
英文:

You have a few options:

  1. Compile your source files individually to object files (this is automatically done with most build setups); then for your particular object file, set custom optimization settings. For example:
cc -O3 file1.c -c -o file1.o
cc -O0 -g file2.c -c -o file2.o

will optimize only file1.c but not file2.c. This works for any compiler.

  1. Use a range-based optimization pragma, a Clang extension. Write #pragma clang optimize off to disable optimizations from that point onward, and #pragma clang optimize on to reenable them. For example, simply putting #pragma clang optimize off at the top of the file will disable optimizations for the entire file.

huangapple
  • 本文由 发表于 2023年7月28日 02:51:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782660.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定