问题描述
如中所述,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) ;
}
通过查看使用您的特定工具链生成的程序的反汇编来验证这一点。
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删除无尽循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!