5

我正在尝试使用与__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;
}

我正在使用 -g -O2 进行构建,但我希望能够进行合理的调试MyDebugabbleFunction()——所以我__attribute__((optimize(0)))在它的声明中使用了。但是,在使用调试器单步执行这两个函数时,我真的看不出任何区别。我希望在尝试单步执行优化代码时通常会看到“看似不稳定”的行为MyNormalFunction,但在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;
}
4

2 回答 2

2

试试这样的测试:

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;
}

这将使它更容易跟随。


请注意main,在逐步执行时,您应该从 开始,因为它很可能会简化为:

int main()
{
    std::cout << 2 << std::endl;
    std::cout << MyDebuggableFunction() << std::endl;
}

如果你愿意的话,看看拆解会让这项任务变得更容易。

于 2012-08-24T17:43:48.460 回答
0

修复代码中的错误后,编译:

g++ -S x.c

_Z16MyNormalFunctionv:
.LFB1255:
    .cfi_startproc
    movl    $2, %eax
    ret

_Z20MyDebuggableFunctionv:
.LFB1256:
    .cfi_startproc
    movl    $0, -4(%rsp)
    movl    $1, -4(%rsp)
    movl    $2, -4(%rsp)
    movl    -4(%rsp), %eax
    ret

如您所见,优化属性运行良好。

于 2012-08-24T17:47:53.327 回答