This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

OPtimization of constants with keil

In my code I have many of constants have same value. I cannot use same name of constant due to logic.

On optimization will keil take different memory of each or same memory.

I am using three setting of optimization:
1. O0
2. Cross + microlib + O2
3. Cross + Time + O3

Parents

  • const int a = 5;
    
    void func(void)
    {
       int b = a * 3;
       //...
    }
    

    I would expect the expression "a * 3" to be evaluated at runtime.

    Care to explain what made you form that expectation? I ask because I'm pretty sure that expectation is unfounded. Any C compiler worth having will make 'a' as unmodifiable as it possibly can (read-only page configured in the MMU, or even actual ROM), and perform 'a*3' at compile time.

    There's absolutely no sane reason for a C compiler to expect 'a', as defined, to ever change past compile time, and therefore no reason for it to delay evaluation of a*3 until runtime. You entered a two-way promise, a.k.a. "contract", with the C compiler by flagging a 'const'. The contract is that neither your code, nor the C compiler, will ever modify 'a'.
    If you plan on violating that contract in ways the C compiler has no way of knowing about (e.g. modifying the hex file before burning, or re-flashing at runtime) it is your responsibility to tell the compiler about that by amending the contract. You do that like this:

    volatile const int a = 5;
    

Reply

  • const int a = 5;
    
    void func(void)
    {
       int b = a * 3;
       //...
    }
    

    I would expect the expression "a * 3" to be evaluated at runtime.

    Care to explain what made you form that expectation? I ask because I'm pretty sure that expectation is unfounded. Any C compiler worth having will make 'a' as unmodifiable as it possibly can (read-only page configured in the MMU, or even actual ROM), and perform 'a*3' at compile time.

    There's absolutely no sane reason for a C compiler to expect 'a', as defined, to ever change past compile time, and therefore no reason for it to delay evaluation of a*3 until runtime. You entered a two-way promise, a.k.a. "contract", with the C compiler by flagging a 'const'. The contract is that neither your code, nor the C compiler, will ever modify 'a'.
    If you plan on violating that contract in ways the C compiler has no way of knowing about (e.g. modifying the hex file before burning, or re-flashing at runtime) it is your responsibility to tell the compiler about that by amending the contract. You do that like this:

    volatile const int a = 5;
    

Children
No data