EmbDev.net

Forum: ARM programming with GCC/GNU tools Preventing GCC from optimizing out variable


von jrmymllr j. (jrmymllr)


Rate this post
useful
not useful
I'm using CodeSourcery GCC for ARM and have this problem where when I 
enable any level of optimization (1,2 or 3), this struct I have defined 
as const is being optimized out.  It's a block of information that I 
have deliberately put into a certain part of flash, so it's not accessed 
by it's struct name, but by address.  GCC insists on removing it unless 
I use -o0.  I have tried to fool it by assigning another variable this 
struct's address, but it doesn't work.  Is there an easy way to simply 
tell GCC not to optimize this away?

von Ernst (Guest)


Rate this post
useful
not useful
You can try to use GCC _attributes_ to mark the structs as "used":
1
struct x y __attribute__((__used__));


http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html

von jrmymllr j. (jrmymllr)


Rate this post
useful
not useful
Darn, didn't work.  No warning or errors, it still discards the struct. 
There doesn't seem to be anything in the documentation for CS GCC about 
this, however.

von Thomas P. (tpircher)


Rate this post
useful
not useful
What about adding a pseudo-assembler instruction that uses the address 
of the variable "my_struct"; something like:
1
__asm__ __volatile__("" :: "m" (my_struct));

von jrmymllr j. (jrmymllr)


Rate this post
useful
not useful
Cool, that worked, thank you.

von Marcus H. (mharnisch)


Rate this post
useful
not useful
Jerry Milner wrote:
> Darn, didn't work.  No warning or errors, it still discards the struct.

What is "it"? Compiler or linker? The attribute only tells the compiler 
that the variable is used, the linker can still toss it out. Check if 
the variable is in the object file.

I am not a GNU expert, but it would appear that the ld-option 
`--print-gc-sections' gives you a report about removed input sections.

Regards
Marcus
http://www.doulos.com/arm/

von jrmymllr j. (jrmymllr)


Rate this post
useful
not useful
I don't know if the linker or compiler discarded it, but after adding 
the _asm_ statement, it appears in the .map file and most importantly, 
the code now works with optimization on.  The struct in question 
contains strings that are displayed in a menu, so it's obvious when this 
struct is missing.

Please log in before posting. Registration is free and takes only a minute.
Existing account
Do you have a Google/GoogleMail account? No registration required!
Log in with Google account
No account? Register here.