我试图__attribute__让一个函数基本上使用与其余代码不同的标志进行编译.例如:
#include <iostream>
#include <vector>
void MyNormalFunction();
void MyDebugabbleFunction() __attribute__((optimize(0)));
void MyNormalFunction()
{
std::cout << "Test" << std::endl;
std::vector<int> a;
for(unsigned int i = 0; i < 10; ++i)
{
a.push_back(i);
}
}
void MyDebugabbleFunction()
{
std::cout << "Test" << std::endl;
std::vector<int> a;
for(unsigned int i = 0; i < 10; ++i)
{
a.push_back(i);
}
}
int main()
{
MyNormalFunction();
MyDebugabbleFunction();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用-g -O2进行构建,但我希望能够进行合理的调试MyDebugabbleFunction()- 所以我使用了__attribute__((optimize(0)))它的声明.但是,当使用调试器单步执行这两个函数时,我无法区分任何差异.我希望在尝试逐步优化代码时通常会看到"看似不稳定"的行为MyNormalFunction,但标准的"-g" - 仅调试器行为MyDebuggableFunction.
是我做错了__attribute__吗?或者我在两个函数中使用了不好的演示代码(即代码没有"优化得很多")?或者我误解了调试器中应该有什么区别?
我正在使用gcc 4.6.
编辑基于GManNickG的建议
我使用了这个代码,并使用-O2 -g构建:
#include <iostream>
#include <vector>
int MyNormalFunction();
int MyDebugabbleFunction() __attribute__((optimize(0)));
int MyNormalFunction()
{
int val = 0; // breakpoint here - debugger does NOT stop here
val = 1;
val = 2;
return val;
} // debugger stops here instead
int MyDebugabbleFunction()
{
int val = 0; // breakpoint here - debugger stops here and steps through the next 3 lines as if it were built with only -g
val = 1;
val = 2;
return val;
}
int main()
{
int a = MyNormalFunction();
std::cout << a << std::endl;
int b = MyDebugabbleFunction();
std::cout << b << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
尝试这样的测试:
int MyNormalFunction()
{
int val = 0;
val = 1;
val = 2;
// should optimize to return 2
return val;
}
int MyDebuggableFunction() __attribute__((optimize(0)));
{
int val = 0;
val = 1;
val = 2;
// could optimize to return 2, but attribute blocks that
return val;
}
int main()
{
// we need to actually output the return values,
// or main itself could be optimized to nothing
std::cout << MyNormalFunction() << std::endl;
std::cout << MyDebuggableFunction() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
这将使它更容易遵循。
请注意,main单步执行时应从 开始,因为它很可能会简化为:
int main()
{
std::cout << 2 << std::endl;
std::cout << MyDebuggableFunction() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
如果您愿意,查看反汇编会使这项任务变得更加容易。