.text variable and optimization issue

Marcin S msporysz06@gmail.com
Wed Jul 4 20:30:00 GMT 2012

2012/7/4 Václav Zeman <vhaisman@gmail.com>:
> On 07/04/2012 07:56 PM, Marcin S wrote:
>> Hello,
>> I'm trying to write a helper functions for arm microcontroller, that
>> will help to determine if program is run for the first time after
>> programming. I'm using STM32 chip, with ability to modify it's flash
>> memory at runtime.
>> The idea is to put const variable into flash memory (.text)  let's
>> name it SIGNATURE, and then, during initialization sequence check for
>> that variable value and eventually change it in flash under it's
>> address (&SIGNATURE). When program will be launched next time, this
>> variable will be already changed, letting you know that this is not a
>> first run.
>> Here is a simple  code snippet to do that
>> const uint16_t CFlashSignature::SIGNATURE = 0xFFFF; //initial value in flash.
>> bool CFlashSignature::isFristRun()
>> {
>>       return *(uint16_t*)&SIGNATURE; //it must be written that way,
>> otherwise program will not always notice change at SIGNATURE's address
>> }
>> void CFlashSignature::setSignature()
>> {
>>       if(isFristRun())
>>       {
>>               FLASH_Unlock();
>>               FLASH_ProgramHalfWord((uint32)&SIGNATURE,0); //this function writes
>> 0 at signature's address
>>               FLASH_Lock();
>>       }
>> }
>> and those functions are working as intended, but inly with NO
>> optimization enabled, when i add any optimization (-Ox) isFirstRun()
>> method always returns true! as if
>> return *(uint16_t*)&SIGNATURE;
>> was translated to
>> return 0xffff;
>> or something, i'm not exactly sure.
> The compiler probably sees through your games. The language defines that
> constants are really, constant, AFAIK. Try changing the 'const uint16_t
> CFlashSignature::SIGNATURE' to 'const volatile uint16_t
> CFlashSignature::SIGNATURE' or just drop the const entirely (and add
> volatile).

Yes, i did tried this before, unfortunately with this modifier
(volatile or omitting const at all) makes variable not to land in
.text (flash) but in RAM, so, this won't do me any good if flag will
reset after power down - i need it to be persistent, thats the whole

>> I could disable optimization for this translation unit as a
>> workaround, but there is no guarantee it stays that way in future
>> versions of gcc or something.
>> So in general, I need 2 byte variable that will be always in .text and
>> it's address should obtainable at any point. Any suggestions how to
>> achieve it to be 100% it will be there?
> --
> VZ

More information about the Gcc-help mailing list