user2011659
user2011659

Reputation: 1107

how to prevent gcc from optimizing away code after infinite loop?

I would like an embedded device to wait before entering a certain state until I can set up the remote debugger via JTAG to continue execution.

I tried to use an infinite loop continuing execution by setting the program counter to the next instruction.

I'm using a constant expression so as the loop doesn't get optimized away as the SEI CERT C Coding Standard states in MSC06-C as compliant example:

while(1);

My problem is now that gcc optimizes away everything following this code in the same function and at first glance I found no gcc option to specifically prevent this.

Is this the right way to do what I want? And how is it done the right way?

Upvotes: 2

Views: 1444

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 58393

I would probably do

volatile int keep_spinning = 1;
while (keep_spinning) ; // spin

This way the compiler cannot prove that the loop is infinite, so it cannot remove it nor anything that follows.

It also gives you a convenient way to continue execution when you are ready: just use your remote debugger to poke the value 0 into the variable keep_spinning.

It may be more convenient if you make it global (or perhaps static), in addition to being volatile. Global variables are likely to be easier for your debugger to find, since they have symbols, and they are less likely to be incorrectly optimized out by buggy compilers like in Eugene Sh.'s comment below.

Upvotes: 3

Related Questions