Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop optimizer discard unused variables?

I would like to debug my code and can't access the internal layer in the process since this would disturb the communication with the hardware. (volatile operations are performed where the watchlist would interfere with the basic read accesses.)

So I'm testing the interface's return values but the IAR compiler does even optimize unused volatile variables away.

and a statement like this:

i = object.foo();
if (i)i=i;

doesn't help either.

I found here on SO just answers that advice for that case to use i/o operations. but that's no option either, since I don't have the option of including the C standard libraries. and the project itself doesn't need i/o there is no own variant of input/output functions.

So what are my options except disabling the optimizer?

like image 438
dhein Avatar asked Sep 16 '15 11:09

dhein


2 Answers

The most reliable way is to find a setting in your linker files that forces a certain variable to get linked. But that's of course completely system-dependent.

Otherwise, the portable standard solution is simply to write (void)i; somewhere in the code. That works for most compilers. If it doesn't, you can take it one step further:

#ifdef DEBUG_BUILD
volatile int dummy;

// all variables you would like to have linked:
dummy = i; 
dummy = j;
...
#endif

Or if you are fond of obscure macros:

#define FORCE_LINKING(x) { void* volatile dummy = &x; }

(void* since that is type generic and works for every kind of variable. * volatile to make the pointer itself volatile, meaning the compiler is forbidden to optimize away the write to it.)

like image 78
Lundin Avatar answered Oct 03 '22 12:10

Lundin


A common way is to put it into a while loop via a macro.

#define KEEP_UNUSED(var) do { (void)var; } while(false);

IAR also has an extension called __root: http://supp.iar.com/FilesPublic/UPDINFO/004350/manuals.htm

The __root attribute can be used on either a function or a variable to ensure that, when the module containing the function or variable is linked, the function or variable is also included, whether or not it is referenced by the rest of the program.

like image 31
HelloWorld Avatar answered Oct 03 '22 12:10

HelloWorld