问题描述
如所述,C ++ 11优化了无限循环
As discussed in this question, C++11 optimizes endless loops away.
然而,在具有单一目的的嵌入式设备中,无限循环是有道理的,实际上经常被使用。即使一个完全空的 while(1);
对于看门狗辅助的复位很有用。终止但空的循环也可以在嵌入式开发中有用。
However, in embedded devices which have a single purpose, endless loops make sense and are actually quite often used. Even a completely empty while(1);
is useful for a watchdog-assisted reset. Terminating but empty loops can also be useful in embedded development.
有没有一个优雅的方式来专门告诉编译器不要删除空的或无尽的循环,而不会完全禁用优化?
Is there an elegant way to specifically tell the compiler to not remove empty or endless loops, without disabling optimization altogether?
推荐答案
要删除的循环(如该问题所述)的要求之一是它
One of the requirements for a loop to be removed (as mentioned in that question) is that it
所以,
void wait_forever(void)
{
volatile int i = 1;
while (i) ;
}
应该/ / em>通过查看使用特定工具链生成的程序的反汇编来验证这一点。
should do the trick, although I would certainly verify this by looking at the disassembly of a program produced with your particular toolchain.
像这样的函数将是GCC的一个很好的候选者属性。
A function like this would be a good candidate for GCC's noreturn
attribute as well.
void wait_forever(void) __attribute__ ((noreturn));
void wait_forever(void)
{
volatile int i = 1;
while (i) ;
}
int main(void)
{
if (something_bad_happened)
wait_forever();
}
这篇关于防止C ++ 11删除无尽循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!