在比较大的 C++ 工程中,为了提高程序执行效率,往往会使用 O2 或 O3 优化等级进行编译。同时为了调试程序,可以加入 “-g” 选项来保留 debug 符号。不过很多时候 O2/O3 优化会导致编译结果与源代码的结构差异很大,比如循环展开和指令集优化可能导致循环消失,函数内联导致无法跳转等,给 debug 过程带来很多麻烦。为此可以强制指定被调试的函数优化等级为 O0,不对整体程序性能产生太大影响的同时,使调试更加方便。
对于 GCC 而言,有三种方法能指定函数优化等级:
- 预处理器
#pragma GCC push_options
#pragma GCC optimize("-O0")
float sum(const std::array<float, 16>& arr)
{
float s = 0;
for(const auto& v : arr)
s += v;
return s;
}
#pragma GCC pop_options
- GCC attributes
__attribute__((optimize(0)))
float sum(const std::array<float, 16>& arr)
{
float s = 0;
for(const auto& v : arr)
s += v;
return s;
}
- C++11 attributes
[[gnu::optimize(0)]]
float sum(const std::array<float, 16>& arr)
{
float s = 0;
for(const auto& v : arr)
s += v;
return s;
}
- 在线示例
- 参考资料